a-exelle
a-exelle

Reputation: 21

Create an object in Visual Basic (not VB.NET) without using "New"

I've been told to think outside the box, and think of a way to create an object in VB without using the new keyword. I was told it is possible but i'm having trouble figuring it out. I know primitive data gets stored on the stack and the reference to the objects get stored there too but the actual memory space for the object is in the heap and that new does that for us. When i try it without new i mostly get null reference exception, any ideas on how this is possible?

Dim objTest as TestOne()

'some class named TestOne with empty Constructor

Upvotes: 0

Views: 1193

Answers (2)

HTTP 410
HTTP 410

Reputation: 17610

In VB you can use the CreateObject function if you have an existing class defined in a COM library that you've created - or a COM library that already exists.

As an example, create a project reference to the Microsoft Scripting Runtime COM library (scrrun.dll). To do this in the VB IDE select Project, References, then pick the reference 'Microsoft Scripting Runtime'. You can then write the following code:

Dim fso As Object
fso = CreateObject("Scripting.FileSystemObject")

Upvotes: 2

ActualRandy
ActualRandy

Reputation: 306

I haven't done VB for quite a while now, but the Activator exists in both C# and VB. Here's couple lines of C# that you can convert to VB:

var newThing = (TestOne)Activator.CreateInstance(typeof(TestOne));
newThing.ID = 5;

The CreateInstance method returns an object, which I convert to the correct class with

(TestOne)

which is the C# syntax for type conversion. Sorry, I forgot how to do this in VB.

Where class 'TestOne' looks like:

class TestOne {
    public int ID { get; set; }
}

Note that 'Activator' is part of .NET reflection.

Upvotes: 1

Related Questions