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)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
intas a boolean expression in C#. Since the only valid boolean expressions are expressions that evaluate directly tobool, this keeps unexpected errors from being introduced in the code, such as the old C gotcha: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
!= nullinside 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)