So I have been intrigued by the ?? operator, but have still been unable to use it. I usually think about it when I am doing something like:
var x = (someObject as someType).someMember;
If someObject is valid and someMember is null, I could do
var x = (someObject as someType).someMember ?? defaultValue;
but almost invariably I get into problems when someObject is null, and ?? doesn’t help me make this any cleaner than doing the null check myself.
What uses have you guys found for ?? in practical situations?
I agree with you that the ?? operator is usually of limited use– it’s useful to provide a fall-back value if something is null, but isn’t useful to prevent a Null Reference Exception in cases when you want to continue drilling down into properties or methods of a sometimes-null reference.
IMHO, what’s needed much more than ?? is a “null-dereference” operator which allows you to chain long property and/or method chains together, e.g.
a.b().c.d().ewithout having to test each intermediate step for null-ness. The Groovy language has a Safe Navigation operator and it’s very handy.Luckily, it seems that the C# team is aware of this feature gap. See this connect.microsoft.com suggestion for the C# team to add a null-dereference operator to the C# language.
If you also want this feature in C#, add your votes to the suggestion on the connect site! 🙂
One workaround I use to get around the lack of this feature is an extension method like what’s described in this blog post, to allow code like this:
This code either returns
h.MetaData.GetExtendedName().Trim().ToLower()or it returns null if h, h.MetaData, or h.MetaData.GetExtendedName() is null. I’ve also extended this to check for null or empty strings, or null or empty collections. Here’s code I use to define these extension methods: