开发者

C# - short check for null

How do I replace the following code

if (customer.Person!=null)
 Console.WriteLine(customer.Pe开发者_JS百科rson.Name);

with something like this

Console.WriteLine(customer.Person.Name?? "unknown");


You can't, I'm afraid - there's nothing like Groovy's null-safe dereferencing operator :(

I suppose you could create a "null object" for Person - i.e. a real instance, but with all the properties null. Then you could use:

Console.WriteLine((customer.Person ?? Person.Null).Name ?? "Unknown");

... but that's pretty horrible. (It's also not checking for customer being null.)

Another option would be to write an extension method on Person:

public static string NameOrDefault(this Person person, string defaultName)
{
    return person == null ? defaultName : person.Name ?? defaultName;
}

Then:

Console.WriteLine(customer.Person.NameOrDefault("Unknown");


You could use the ternary operator:

Console.WriteLine(customer.Person != null ? customer.Person.Name : "unknown");

Not the best-looking code, but still a one-liner.


Edit: don't forget to use IsNullOrWhiteSpace, in case your application logic treats empty & null strings the same.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜