Reputation: 5683
The following shows MyEmpty, which is "" while I thought it would be null.
public class SomeClass
{
public static readonly String MyEmpty;
...
}
If MyEmpty is "" rather than null, does it have to be going like this below?
public class SomeClass
{
public static readonly String MyEmpty = "";
...
}
Somehow the 'readonly' makes that happen but why?
Thanks in advance.
[Edit]
I was testing these two using MessageBox.Show() assuming that the method would throw an exception when I give it a null value. But it didn't throw any exception at all, which is why I thought that in my first code MyEmpty was not null but "".
Thank you all for trying to explain the difference between null and "" and also my mistake.
Upvotes: 0
Views: 452
Reputation: 6070
The compiler do not allow empty structs, therefor stuff like readonly params and props get the initial value "" or 0 for int etc. Because theoreticaly you are not suppose to assign them while declaring one inside a method it would give you an exception.
Upvotes: 0
Reputation: 1
string.Empty is the same as "", which is a string of 0 length.
While Null means there is No string.
Upvotes: 1
Reputation: 4340
With your first code MyEmpty should be null.
public class SomeClass
{
public static readonly String MyEmpty; <- Gets null
...
}
you specified the "readonly" keyword so i guess the only place you changed it's value to "" is in the constructor.
The reason that you can't get "" without specifying it is that the empty string "" needs to be allocated (unless you reference string.empty) so it can't be that you get that value by default
Upvotes: 1
Reputation: 27927
String is a reference type. An empty string is something different than string = null. Second means there's no reference to a string object.
Upvotes: 0