Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.Net Alternative to C# Underscore (discard)

Tags:

vb.net

In c# i can do:

_ = Bla();

Can I do that in VB.Net ?

I think the answer is no but I just wanted to make sure.

like image 604
Shereef Marzouk Avatar asked Aug 02 '19 19:08

Shereef Marzouk


1 Answers

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.

like image 110
Heinzi Avatar answered Oct 08 '22 21:10

Heinzi