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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
?? Operator (C# Reference)
http://msdn.microsoft.com/nl-be/library/ms173224(en-us).aspx
http://msdn.microsoft.com/nl-be/library/ms173224(en-us).aspx
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
^^^ 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.
ASKER
Hi oxyoo,
The only doubt I have is this. If myClass is null, wouldn't myClass.ShowHeader throw an NullReferenceexception?
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" :)
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" :)
Open in new window