Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we do 'if (object)' in C# to test if object is null?

Tags:

c

c#

object

null

In C, in order to test if a pointer is null we can do:

  • if (p != NULL)
  • if (p != 0)
  • if (p)

Why isn't there any equivalent in C# that would allow us to do the following?

if (object)

instead of

if (object != null)
like image 896
Otiel Avatar asked Nov 17 '11 15:11

Otiel


1 Answers

Because tests of that nature could lead to unexpected bugs in programs, thus they favored requiring boolean expressions to be explicit (as did Java), instead of performing an implicit conversion to bool.

This is also the same reason why you cannot use an int as a boolean expression in C#. Since the only valid boolean expressions are expressions that evaluate directly to bool, this keeps unexpected errors from being introduced in the code, such as the old C gotcha:

if (x = 5)
{ 
   // always true
}

So, in short, it was not included in order to favor readability and explicitness. Yes, it does come at a slight cost in brevity, but the gains in reduction of unexpected bugs more than make up for the cost of hainvg to add != null inside the parenthesis...

(You can, of course, create an implicit conversion of a custom type to bool, as a workaround, but you can't globally apply that to any object type)

like image 195
James Michael Hare Avatar answered Nov 15 '22 19:11

James Michael Hare