Jared Parsons is right (obviously), and this isn't a matter of opinion. There are concrete advantages. Use is object
or is null
when you can. It looks unusual now, but will become far more common in the future.
Up until C# 7, is
was only used in type checking. Starting with C# 7 though, it's also used for pattern matching. is null
is a constant pattern that matches when the input is exactly null
. is object
or is string s
match on the type.
is null
and is object
are preferable because someone can overload the Equals
and ==
operators. For example, two boxes with equal sizes can be considered equal. x==null
uses the type's equality operator and will only return true if that operator says it's true.
What happens though if there's a mistake, or if someone tried to get clever with equality? And why should we waste CPU to call that operator when we only need to know if that value is null?
One of the answers to the question Operator overloading ==, !=, Equals shows the problem :
The code in operator ==()
:
public class BOX
{
public double Height{get;set;}
public double Length{get;set;}
public double Breadth{get;set;}
public static bool operator == (BOX b1, BOX b2)
{
if ((object)b1 == null)
return (object)b2 == null;
return b1.Equals(b2);
}
...
Started as :
public static bool operator == (BOX b1, BOX b2)
{
if (b1 == null)
return (b2 == null);
return b1.Equals(b2);
}
Oops - that's infinite recursion! Each of those comparisons ends up calling operator ==
again. If our own code used :
if (theBoxFromDB == null) ...
We'd get an infinite recursion too. The answerer fixed this by casting to object
, thus forcing a comparison using Object.Equals
.
We can avoid such unfortunate situations though if we use :
if (theBoxFromDB is null) ...
The equality operator itself can be simplified this way. No extra casts, no calls to ReferenceEquals
the way other answers do. :
public static bool operator == (BOX b1, BOX b2)
{
if (b1 is null)
return (b2 is null);
return b1.Equals(b2);
}
Things get more interesting when we start using the full pattern matching syntax. In if(box is null)
the only thing we know is that the box is null
.
If we use the syntax is T name
though, we get a strongly typed, non-null variable :
object box=LoadFromSomewhere();
if(box is Box b)
{
var volume=box.Height*box.Width*box.Breadth;
}