qJake
qJake

Reputation: 17139

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?

Upvotes: 2

Views: 513

Answers (4)

Brian M.
Brian M.

Reputation: 826

If you're explicitly wanting to call a sub and not a function, you can:

Call (New obj).Func()

Which will anonymously create a new obj, and call its Func() method

Upvotes: 2

Ahmad Mageed
Ahmad Mageed

Reputation: 96557

In addition to Hans' answer, you could use a With statement:

Sub Main
    With New Person("Ahmad")
        .PrintName()
        .Name = "Mageed"
        .PrintName()
    End With
End Sub

Public Class Person
    Public Property Name As String
    Public Sub New(ByVal name As String)
        Me.Name = name
    End Sub

    Public Sub PrintName()
        Console.WriteLine("Name: {0} - Len: {1}", Name, Name.Length)
    End Sub
End Class

It's not as succinct as C#, but the reference to the object is discarded after End With.

Upvotes: 2

mdm
mdm

Reputation: 12630

You can do lambda functions in VB.NET like this:

Dim test = Function (x)
    x.doStuff()
End Function

Which would be semantically equivilent to:

var test = (x) => x.doStuff();

I think the one constraint though is that it must return a result under VB.NET.

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 942518

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.

Upvotes: 4

Related Questions