Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing an object without assigning it in Visual Basic.NET

Tags:

vb.net

I've used VB.net for several years now, but keep coming across little quirks that I don't know how to work around. Curiosity finally got the best of me, so I ask now: is there a way to create an object without assigning it?

For example, say I have an Engine class, that I want to instantiate and have it immediately do whatever it needs to do. If there's nothing I need to do with Engine after creating it, I have, till now, done something like:

dim myEngine as new Engine()

Is there a way to avoid the "dim myEngine as" part? You certainly can in Java. I could just create an object with "new Engine()" in java and not assign it to anything.

Why do I need this? Because often I want to create a delegate object (hence I called it "engine") that performs some functionality, but otherwise I don't need to ever reference it. I used to have such objects have a "public sub perform", but have found that cumbersome -- I'd rather just create the object and not worry about remembering to call its perform method. And I find it aesthetically displeasing to create references to objects that I don't intend to use.

Any VB guru have a suggestion?

Thanks,

-- Michael

like image 200
Michael Zlatkovsky Avatar asked May 03 '26 04:05

Michael Zlatkovsky


1 Answers

To do this you need to put the New declaration inside Parentheses ( )

you can try this syntax:

Call New TheClass().Method1()

or:

DoSomething(New TheClass())

or even:

DoSomething(New TheClass().GetStringData())

Source: http://tutorials.beginners.co.uk/vb-net-programming-part-6-interacting-with-objects.htm

like image 171
Tony Avatar answered May 06 '26 04:05

Tony