How to assign a value of a property to a var ONLY if the object isn't null

Posted by Blankman on Stack Overflow See other posts from Stack Overflow or by Blankman
Published on 2010-04-11T05:52:06Z Indexed on 2010/04/11 6:03 UTC
Read the original article Hit count: 206

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about null