Add null-propagating member-access operator (?.) to VB.NET
I've heard a similar feature is possibly in the pipeline for C#, and would love to see it in VB.NET as well. I'd love to reduce:
If points IsNot Nothing Then
Dim next = points.FirstOrDefault
If next IsNot Nothing AndAlso next.X IsNot Nothing Then
Return If(points?.FirstOrDefault()?.X, -1)
It is a very common problem to have to write code such as...
If Order IsNot Nothing AndAlso Order.Customer IsNot Nothing Then cname = Order.Customer.Name
What would be really useful would be to have a special member access operator that would return Nothing/null when the object that you are accessing is null. eg. if we used the pipe character...
cname = Order|Customer|Name
This would set cname to Nothing if either Order Is Nothing or Order.Customer Is Nothing. If neither of them are, it would return Order.Customer.Name
We’ve gotten a tremendous amount of feedback from users that this feature would be valuable. We’d really like to do it in the next version and are fleshing out the design now. It’s a feature that we’d do for both VB and C# at the same time.
At the moment the most commonly imagined syntax is ‘?.’ well technically the operator itself is just ? and it modifies whatever comes after so all of these cases would potentially result in null if the expression to the left of the ? is null:
’ Null-propagating member-access.
’ Null-propagating object index or delegate invocation.
’ Null-propagating dictionary-access.
’ Null-propagating XML element-, attribute-, and descendent-access.
(for C# we’d also need to consider ?→ for null-propagating pointer dereference)
The design seems mostly straight-forward though we still need to think about possible interactions with the Await operator (would there be an Await??) and VB’s flexibility on parentheses for indexing the results of method calls. But hopefully we should have all of that figured out in a week.
Anthony D. Green | Program Manager | Visual Basic & C# Languages Team
Mike C commented
I could imagine GetList?(0)?.Property, which is workable but does move away from the "spirit" of VB a little, as the sequence of characters starts to look more like a regex or something. (Not that I'd typically write a method that returns Nothing when a list is expected; I'd rather return an empty list.)
However, I don't have any insight in how null-propagation would work with the Await keyword.