8

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?

asked Jul 8, 2013 at 12:43
8
  • 6
    s is not a string, it's a null reference. If it referred to something, that something would be a string. Commented Jul 8, 2013 at 12:44
  • 3
    however 'bool b = typeof(s) is string;' would yield the expected result Commented Jul 8, 2013 at 12:45
  • no i dont get null refrence Commented Jul 8, 2013 at 12:45
  • 2
    Read What the meaning of is is by Eric Lippert :) Commented Jul 8, 2013 at 12:45
  • 1
    There is a difference between is in the english language and is in the C# programming language. Commented Jul 8, 2013 at 12:45

3 Answers 3

4

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/

answered Jul 8, 2013 at 12:48

2 Comments

I'm not seeing how the typeof operator would be of any help in this situation.
@m-y If the OP is looking for the Type object of string, he can use typeof instead of the is operator.
1

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'.

answered Jul 8, 2013 at 12:46

Comments

0

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.

answered Jul 8, 2013 at 12:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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