开发者

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 ca开发者_运维知识库n 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.


Your syntax on the second is slightly off.

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


In c# 6.0 you can now do

string username = SomeUserObject?.Username;

username will be set to null if SomeUSerObject is null. If you want it to get the value "", you can do

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


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

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


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

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


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


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.


It is called null coalescing and is performed as follows:

string username = SomeUserObject.Username ?? ""
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜