Search code examples
c#null

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


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.


Solution

  • Your syntax on the second is slightly off.

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