vb.net

VB.NET alternative to the C# discard operator (underscore)


In C#, you can do the following:

_ = Bla();

Is this possible to do in VB.NET as well? (I think the answer is no, but I just want to make sure.)


Solution

  • The underscore (_), as used in your example, is C#'s discard token. Unfortunately, there is (currently) nothing similar in VB. There is a discussion about adding a similar feature on the VB language design github page.

    In your example, however, you can just omit assigning the result (both in C# and VB), i.e.

    Bla(); // C#
    
    Bla()  ' VB
    

    The "discard variable" is particularly useful for out parameters. In VB, you can just pass an arbitrary value instead of a variable to discard unused ByRef parameters. Let me give you an example:

    The following two lines are invalid in C#:

    var b = Int32.TryParse("3", 0); // won't compile
    var b = Int32.TryParse("3", out 0); // won't compile
    

    Starting with C# 7, you can use _ for that purpose:

    var b = Int32.TryParse("3", out _); // compiles and discards the out parameter
    

    This, however, is perfectly valid in VB, even with Option Strict On:

    Dim b = Int32.TryParse("3", 0)
    

    So, yes, it would be nice to make the fact that "I want to ignore the ByRef value" more explicit, but there is a simple workaround in VB.NET. Obviously, once VB.NET gets pattern matching or deconstructors, this workaround won't be enough.