Alexandre
Alexandre

Reputation: 13308

C# - short check for null

How do I replace the following code

if (customer.Person!=null)
 Console.WriteLine(customer.Person.Name);

with something like this

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

Upvotes: 6

Views: 15387

Answers (2)

HuBeZa
HuBeZa

Reputation: 4761

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.

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1499770

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");

Upvotes: 11

Related Questions