Link to home
Start Free TrialLog in
Avatar of vbhargav80
vbhargav80

asked on

?? operator in C#

Dear Experts,

I want to know if I can do this in C#

MyClass
{
   public bool ShowHeader {return true;}
}

AnotherClass
{
   MyClass myClass = GetInstanceOfMyClass()

   return myClass.ShowHeader ?? false;
}

Basically if the myClass object is null i want to return false otherwise the value of myClass.SHowHeader
ASKER CERTIFIED SOLUTION
Avatar of oxyoo
oxyoo
Flag of Sweden image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Haven't seen such an operator, but for sure you can do something like:
return myClass == null ? false : myClass.ShowHeader;

Open in new window

Avatar of Dirk Haest
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
^^^ if you function returns a bool type (which I've just noticed it does after re-reading the question :) ), then any of the above answers should suffice... but as I said, if the creation of a class fails then you should consider throwing an exception if this is an error condition and not an expected state.
Avatar of vbhargav80
vbhargav80

ASKER

Hi oxyoo,

The only doubt I have is this. If myClass is null, wouldn't myClass.ShowHeader throw an NullReferenceexception?
@vbhargav80
Well the code states if myClass is not (!=) null then it will call ShowHeader. If it is null then it will return false and ShowHeader will not be called at all. So there shouldn't be any problem.
@alb66
The if-statement is more readable I guess, but I favor (as far as possible) to use only one exit point in a method to reduce complexity and make it less error prone. Not a big deal in a small method like this perhaps. Perhaps a matter of  "design-taste" :)