J
Jon Skeet [C# MVP]
Thomas W. Brown said:Actually, there is one difference between the two... If "something"
is a class that overrides operator ==, then
if (null == something)
will always be a quick object reference comparison returning 'true'
when something is a null reference and 'false' when not.
But,
if (something == null)
will, if something is not null, be calling a subroutine only to do
the comparison against null and return false. Performance-wise, then,
the first version might offer slight improvements.
No, they'll both call the overloaded operator. See section 14.2.4 of
the C# language specification for details.
Here's a test program to show that happening:
using System;
class Foo
{
public static bool operator == (Foo y, Foo x)
{
return true;
}
public static bool operator != (Foo y, Foo x)
{
return false;
}
public override int GetHashCode()
{
return 0;
}
public override bool Equals (object o)
{
return true;
}
}
public class Test
{
static void Main()
{
Foo x = new Foo();
if (x==null)
{
Console.WriteLine("Hello");
}
if (null==x)
{
Console.WriteLine("Hello");
}
}
}