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