user1968030
user1968030

Reputation:

Why null 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 above code s is string but b is false.

actually s as string,Why i get this result ?

Why compiler has this behavior?

Upvotes: 8

Views: 218

Answers (3)

Ant P
Ant P

Reputation: 25221

The null keyword is a literal that represents a null reference, one that does not refer to any object.

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

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

Upvotes: 0

David Pfeffer
David Pfeffer

Reputation: 39833

When evaluating your statement, the runtime must first follow the reference to which the variable refers. Only then may it evaluate the referenced object to determine if it is indeed a string.

Since a null reference refers to no object, it is not a string. In fact, it is nothing at all.

You can use the typeof operator to get the Type object that corresponds to string, rather than compare a referenced object, if that's your ultimate goal.

This is actually the particular example given by Eric Lippert in a blog post on this very subject:

I've noticed that the is operator is inconsistent in C#. Check this out:

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/

Upvotes: 4

codebox
codebox

Reputation: 20254

The variable s is a reference that can potentially point to the location of a string in memory, however you haven't pointed it at a string yet - it points to 'null'. When you ask s is string you are saying 'does the reference s point to the location of a string in memory' and in your case the answer is 'no'.

Upvotes: 1

Related Questions