Is there an abbreviation in my code that I can use to assign a variable the value of an object property ONLY if the object is not null?
string username = SomeUserObject.Username; // fails if null
I know that I can check, for example, if (SomeUserObject! = Null), but I think I saw an abbreviation for such a test.
I tried:
string username = SomeUserObject ?? "" : SomeUserObject.Username;
But that does not work.
Your syntax on the second is slightly off.
string name = SomeUserObject != null ? SomeUserObject.Username : string.Empty;
Closest you will understand that:
string username = SomeUserObject == null ? null : SomeUserObject.Username;
# 6.0
string username = SomeUserObject?.Username;
null, SomeUSerObject null. "",
string username = SomeUserObject?.Username ?? "";
, , , :
string username = (SomeUserObject != null) ? SomeUserObject.Username : null;
?: , Null, User User.NotloggedIn, .
User.NotloggedIn
.Username.
.Username
: / (null), ( ), - .
NotloggedIn , NotLoggedIn, , , , , , ,...
, , if (someuser is NotLoggedIn) ...
if (someuser is NotLoggedIn) ...
.
string username = SomeUserObject == null ? "" : SomeUserObject.Username;
. http://msdn.microsoft.com/en-us/library/ty67wk28.aspx.
:
string username = SomeUserObject.Username ?? ""