Search code examples
vb.netequivalentnull-check

VB equiv - Elegant way to check if a property's property is null


I noticed this great post on how to do inline null checks on nested objects/properties: C# elegant way to check if a property's property is null

Is there a VB.NET equivalent available?


Solution

  • Yes. The null-conditional operator (MSDN) also exists in VB.NET (VB 14 and above, i.e., Visual Studio 2015 and above) and has the same syntax:

    Dim value As Int32? = objectA?.PropertyA?.PropertyB?.PropertyC
    

    Often, this is combined with the null-coalescing operator, which is a ?? b in C# and If(a, b) in VB.NET:

    Dim value As Int32 = If(objectA?.PropertyA?.PropertyB?.PropertyC, 0)  ' Default value if null