tags:

views:

87

answers:

6

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.

A: 

It is called null coalescing and is performed as follows:

string username = SomeUserObject.Username ?? ""
JP
Will still fail if SomeUserObject is null.
micahtan
SomeUserObject could be null. He should be using the conditional operator and checking his object for null.
Anthony Pegram
You guys are correct - i misread the question, sorry!
JP
+3  A: 

Your syntax on the second is slightly off.

string name = SomeUserObject != null ? SomeUserObject.Username : string.Empty;
Anthony Pegram
+2  A: 

The closest you're going to get, I think, is:

string username = SomeUserObject == null ? null : SomeUserObject.Username;
Michael Petrotta
+1  A: 

This is probably as close as you are going to get:

string username = (SomeUserObject != null) ? SomeUserObject.Username : null;
Taylor Leese
A: 

You're thinking of the ternary operator.

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

See http://msdn.microsoft.com/en-us/library/ty67wk28.aspx for more details.

micahtan
+1  A: 

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) ...

Hightechrider