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?
3 Answers 3
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/
2 Comments
typeof
operator would be of any help in this situation.Type
object of string, he can use typeof
instead of the is
operator.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'.
Comments
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.
s
is not a string, it's a null reference. If it referred to something, that something would be a string.is
in the english language andis
in the C# programming language.