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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With