why this doesn't throw an exception
it's kind a simple question but i have the doubt see the code belows
public static String something;
static void Main(string[] args)
{
try
{
if (something == "blah")
System.Console.Write("ok");
}
catch (Exception)
{
throw;
}
}
i know that doesn't throw an exception but why? because the variable with the name something it's null and when you compare you开发者_JAVA百科're trying to get a reference with null. Can someone please explain to me why? Thanks!
Nothing is wrong here, since you're not trying to dereference something
. You are getting its value, which is null
. If you tried to dereference it (ie something.somemethod()
) then an exception would have been thrown.
This is IL code generated by compiler:
IL_0002: ldsfld string ConsoleApplication1.Program::something IL_0007: ldstr "blah" IL_000c: call bool [mscorlib]System.String::op_Equality(string, string)
String.op_Equality Method:
public static bool operator == (string a, string b)
a - A String or a null reference
b - A String or a null reference
op_Equality allows to pass null references and doesn't throw exception.
The variable, something, doesn't need to be instanced for that kind of comparison. It knows how to compare itself to a null.
So it doesn't throw an exception because
null == "string"
is a valid comparison which returns false.
You can compare null to a string - the result is that they aren't equal. In this case Something is null - you don't have to "dereference" to use it in a comparison, the null value itself works.
since the something variable is null, then comparing it to a string value is the same as saying
if(null == "blah")...
Clearly null and "blah" are not the same, so it will return false, it won't throw an exception.
A string is a nullable type.
So you in the given code you compare a NULL string to a string that contains the characters "blah" and you have no else statement.
Of course I would argue using == when you are trying to compare a string is wrong.
Technically "Dog played ball with the boy\n" and "Dog played ball with the boy\0" would not equate to true when using the == comparison.
精彩评论