C # - short check for zero

How to replace the following code

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

with something like this

Console.WriteLine(customer.Person.Name?? "unknown");
+5
source share
2 answers

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

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

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

... but it's pretty terrible. (It also does not verify that the value customeris null.)

Another option is to write an extension method for Person:

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

Then:

Console.WriteLine(customer.Person.NameOrDefault("Unknown");
+11
source

You can use the thermal operator :

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

Not the most beautiful code, but still single-line.


: IsNullOrWhiteSpace, .

+5

All Articles