I suggest you ...

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 next.X
End If
End If
Return -1

...to:

Return If(points?.FirstOrDefault()?.X, -1)

15 votes
Vote
Sign in
Check!
(thinking…)
Reset
or sign in with
  • facebook
  • google
    Password icon
    I agree to the terms of service
    Signed in as (Sign out)
    You have left! (?) (thinking…)
    Mike CMike C shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →
    Martin RossMartin Ross shared a merged idea: Create a new operator for accessing members on objects that may be null  ·   · 

    Hey Mike,

    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.
    list?.Member

    ’ Null-propagating object index or delegate invocation.
    list?(0)

    ’ Null-propagating dictionary-access.
    list?!key

    ’ Null-propagating XML element-, attribute-, and descendent-access.
    list?.
    list?.@attribute
    list?…

    (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.

    Regards,

    Anthony D. Green | Program Manager | Visual Basic & C# Languages Team

    1 comment

    Sign in
    Check!
    (thinking…)
    Reset
    or sign in with
    • facebook
    • google
      Password icon
      I agree to the terms of service
      Signed in as (Sign out)
      Submitting...
      • Mike CMike C commented  ·   ·  Flag as inappropriate

        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.

      Feedback and Knowledge Base