Why an empty string is not a string object

Consider this code:

class Program { static void Main(string[] args) { string s = null; bool b = s is string; Console.WriteLine(b); } } 

In the above code, s is string , but b is false .

actually s like a string, Why am I getting this result?

Why does the compiler have this behavior?

+8
string c #
source share
3 answers

When evaluating your statement, the runtime must first follow the link to which the variable belongs. Only then can he evaluate the object referenced to determine if this is a string.

Since the null reference refers to the absence of an object, this is not a string. In fact, this does not mean anything.

You can use the typeof operator to get a Type object that matches the string, instead of comparing the reference object if that is your ultimate goal.

This is actually a concrete example given by Eric Lippert on a blog post on this subject:

I noticed that the C operator is incompatible with C #. Check this:

 string s = null; // Clearly null is a legal value of type string bool b = s is string; // But b is false! 

What's up with that?

- http://ericlippert.com/2013/05/30/what-the-meaning-of-is-is/

+5
source share

The s variable is a reference that could potentially point to the location of a string in memory, but you haven't pointed it to a string yet - it points to "null". When you ask s is string , you say: "does the s reference point to the location of the string in memory", and in your case the answer is no.

+2
source share

The null keyword is a literal representing a null reference that does not apply to any object .

http://msdn.microsoft.com/en-us/library/edakx9da.aspx

s is string false because s does not refer to an instance of string - s is null.

+1
source share

All Articles