Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

c# - Empty string if null

I have this in my code:

SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString())

It gives a error when it returns null, how can I make it CustomerID is an empty string if it is null?

/M

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

(Update for C# 6.0)

If you are using C# 6 or newer (Visual Studio 2015 or newer), then you can achieve this using the null-conditional operator ?.:

var customerId = cu.Customer?.CustomerId.ToString() ?? "";

One useful property of the null-conditional operator is that it can also be "chained" if you want to test if several nested properties are null:

// ensure (a != null) && (b != null) && (c != null) before invoking
// a.b.c.CustomerId, otherwise return "" (short circuited at first encountered null)
var customerId = a?.b?.c?.CustomerId.ToString() ?? "";

For C# versions prior to 6.0 (VS2013 or older), you could coalesce it like this:

string customerId = cu.Customer != null ? cu.Customer.CustomerID.ToString() : "";

Simply check if the object is non-null before you try to access its members, and return an empty string otherwise.

Apart from that, there are situations where null object pattern is useful. That would mean that you ensure that your Customer's parent class (type of cu in this case) always return an actual instance of an object, even if it is "Empty". Check this link for an example, if you think it may apply to your problem: How do I create a Null Object in C#.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...