How to assign a property value to var ONLY if the object is not null

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.

+5
source share
7 answers

Your syntax on the second is slightly off.

string name = SomeUserObject != null ? SomeUserObject.Username : string.Empty;
+3
source

Closest you will understand that:

string username = SomeUserObject == null ? null : SomeUserObject.Username;
+2
source

# 6.0

string username = SomeUserObject?.Username;

null, SomeUSerObject null. "",

string username = SomeUserObject?.Username ?? "";
+2

, , , :

string username = (SomeUserObject != null) ? SomeUserObject.Username : null;
+1

?: , Null, User User.NotloggedIn, .

.Username.

: / (null), ( ), - .

NotloggedIn , NotLoggedIn, , , , , , ,...

, , if (someuser is NotLoggedIn) ...

+1

.

string username = SomeUserObject == null ? "" : SomeUserObject.Username;

. http://msdn.microsoft.com/en-us/library/ty67wk28.aspx.

0

:

string username = SomeUserObject.Username ?? ""
-1

All Articles