In my code, is there a shorthand that I can use to assign a variable the value of a object's property ONLY if the object isn't null?
string username = SomeUserObject.Username; // fails if null
I know I can do a check like if(SomeUserObject != null) but I think I saw a shorthand for this kind of test.
I tried:
string username = SomeUserObject ?? "" : SomeUserObject.Username;
But that doesn't work.
To check if it is null, we call the isNull() method and pass the object getUserObject as a parameter. It returns true as the passed object is null.
Using the not equal operator ( variable != null ) Using the Objects class nonNull() method.
The null conditional is a form of a member access operator (the .). Here's a simplified explanation for the null conditional operator: The expression A?. B evaluates to B if the left operand (A) is non-null; otherwise, it evaluates to null.
Your syntax on the second is slightly off.
string name = SomeUserObject != null ? SomeUserObject.Username : string.Empty;
In c# 6.0 you can now do
string username = SomeUserObject?.Username;
username will be set to null if SomeUSerObject is null. If you want it to get the value "", you can do
string username = SomeUserObject?.Username ?? "";
The closest you're going to get, I think, is:
string username = SomeUserObject == null ? null : SomeUserObject.Username;
This is probably as close as you are going to get:
string username = (SomeUserObject != null) ? SomeUserObject.Username : null;
You can use ? : as others have suggested but you might want to consider the Null object pattern where you create a special static User User.NotloggedIn
and use that instead of null everywhere.
Then it becomes easy to always do .Username
.
Other benefits: you get / can generate different exceptions for the case (null) where you didn't assign a variable and (not logged in) where that user isn't allowed to do something.
Your NotloggedIn user can be a derived class from User, say NotLoggedIn that overrides methods and throws exceptions on things you can't do when not logged in, like make payments, send emails, ...
As a derived class from User you get some fairly nice syntactic sugar as you can do things like if (someuser is NotLoggedIn) ...
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