Reputation: 33
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#.
Upvotes: 3
Views: 1283