FastAl FastAl -3 years ago 105 Question

'Null-Safe' Dot notation in VB.NET ... or does it exist in any language? 'safe dereferencing operator' or equivalent using LINQ?

I'm looking for a 'safe' dot notation in Does such a thing exist - in VB.NET or any language? What I want to be able to do is, when using non-nullable legacy objects, to solve a problem like:

"if there as a plan, if there is a case, if it has a person, that person's spouse, else, nothing (VBSpeak for Null)."

and avoid doing this:

Dim Spouse as Person = Nothing
if Case.Plan isnot nothing then
if Case.Plan.Person isnot Nothing
Spouse = Case.Plan.Person.Spouse
end if
end if

and do this:

Dim Spouse as Person = Case~Plan~Person~Spouse

is my sought 'safe' dot notation, which immeditely returns a null upon encountering the first null object instead of throwing an exception?

More common for this problem of course:

dim MyVar as string = XMLDoc.DocumentElement.SelectSingleNode("Name").InnerText

and wanting Nothing instead of an exception when Name doesn't exist.


Is there a way to solve this problem using LINQ for objects or LINQ for XML?

Answer Source

VB.NET 14 introduced the null-conditional operator to address this. This operator is also short-circuiting.

Dim Spouse as Person = Case?.Plan?.Person?.Spouse

Used to test for null before performing a member access (?.) or index (?[) operation. These operators help you write less code to handle null checks, especially for descending into data structures.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download