0

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.

2
  • Are you assigning it to String.Empty somewhere? Because String.Empty is an empty string (i.e. "") and not a null. It isn't the same thing. Commented May 23, 2012 at 6:23
  • Well Empty is assigned "" in the constructor of string Commented May 23, 2012 at 6:36

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Wait, you are absolutely right. I was testing the two code using MessageBox.Show() and totally forgot that the method takes null value as well, without throwing any exception.
Add a breakpoint to before the MessageBox.Show executes, and then you can check the value by pointing with the mouse on MyEmpty
I just did. Thank you so much :)
1

string.Empty is the same as "", which is a string of 0 length.

While Null means there is No string.

1 Comment

So the class string's constructor initializes string.Empty like Empty = ""?
0

String is a reference type. An empty string is something different than string = null. Second means there's no reference to a string object.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.