3

I would like to create an instance of an object and execute a method of the object, but not go through the extra step of storing that instance in a declared variable.

For example, suppose I have a simple Adder class:

public class Adder
{
    private int m_int1;
    private int m_int2;
    public Adder(int int1, int int2)
    {
        this.m_int1 = int1;
        this.m_int2 = int2;
    }
    public int getSum()
    {
        return m_int1 + m_int2;
    }
}

I can of course create an instance, store in a variable, and use it:

Adder a = new Adder(1, 2);
int rslt = a.getSum();
// rslt = 3

However, in C#, I can skip the variable storage step, and just call the method on the result of the instantiation:

int rslt = new Adder(1, 2).getSum();
// rslt = 3

I can't seem to do the same in VB.NET, however. A statement like:

New Adder(1, 2)

is considered a syntax error unless the result is stored in a variable.

The workaround would be to create a static "Create" method in the class that returns a new instance of the class, but I was wondering if there is a VB.NET equivalent to what's possible in C#.

1
  • 2
    Did you try Dim result as Int32 = (New Adder(1, 2)).getSum()? (which is what you were doing in your c# example) Commented Oct 10, 2013 at 17:18

1 Answer 1

10

Try this:

Dim rslt As Integer = New Adder(1, 2).getSum()
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, yes, you're right. I had run into the problem and done some initial tests based on a non-returning object method (sub). I had assumed that because the non-returning case didn't work, the returning case wouldn't either. New MyObject().DoSomethingNoReturn() doesn't work, but Dim rslt = New MyObject().DoSomethingWithReturn() does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.