int
and object
have a parameterless constructor. Why not string
?
As said before, strings are immutable and therefore if you manipulate a string you actually create a new one every time.
Example:
string s = "str"; // str was created in the memory.
s += "2"; // str2 was created in the memory.
Use StringBuilder when you want to manipulate string(that's why you wanted an empty ctor, right?)
Why indeed?
It would be completely logical and sensical to provide a parameterless constructor for the string
type, yet it doesn't have one.
The reason is because the designers of that type thought it would be a much better idea to have string.Empty
.
There could be a logical reason for having the ability to construct multiple empty strings that are different instances. I fail to see one off the top of my head, but that doesn't mean someone else can't see one.
There are some technical reasons behind why limiting the usage to string.Empty
might be a good idea. First, all empty strings are considered equal, though not necessarily ReferenceEquals
, so having multiple empty strings would seemingly make no sense. The second you say that "I have these two seemingly similar things, yet I've attached a different meaning to each" then perhaps you're trying to solve a problem with the wrong tool.
There's also some upshots of having a predefined string.Empty
. Whenever you reference it, you're referencing the same object instance as every other place, and thus you don't have lots of empty (and identical) string objects in memory.
But could it be done? Sure.
So while everybody here has tried to justify that there should be no such constructor, I am saying that there could be such a constructor.
However, someone decided to design the type without one.