Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET equivalent of a nameless variable in C#?

In C#, you can do this:

new MyClass().MyMethod();

The method is executed and the reference is (typically) discarded since no reference to the object is kept.

My question is: Is this possible with VB.NET (.NET v4)?


Edit: I suppose this is a better example:

new Thread((x) => doSomething()).Start();

Is this even possible in VB.NET?

like image 423
qJake Avatar asked Dec 01 '25 01:12

qJake


1 Answers

VB.NET has stricter rules about the syntax of a statement. The curly-brace languages allow any expression to also be a statement, simply by terminating it with a semi-colon. That's not the case for VB.NET. You can only use this syntax if the method you call is a Function. Which allows you to use the assignment statement:

    Dim result = New Test().Func()

If it is a Sub then you'll have to use the assignment statement to store the object reference. This otherwise has no runtime effect, the reference is optimized away.

like image 136
Hans Passant Avatar answered Dec 02 '25 19:12

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!