Creating an object using a type variable

R

Ramez

Hi
I need to create an object of a class using a type variable.
for example, instead of writing:
X = new MyClass
I want to write something like:
Dim t as Type = GetType(MyClass)
X = CreateObjectFromType(t)

is this possible?
 
C

Carlos J. Quintero [.NET MVP]

Yes:

X = System.Activator.CreateInstance(t)

--

Carlos J. Quintero

MZ-Tools 4.0: Productivity add-ins for Visual Studio .NET
You can code, design and document much faster.
http://www.mztools.com
 
H

Herfried K. Wagner [MVP]

Ramez said:
I need to create an object of a class using a type variable.
for example, instead of writing:
X = new MyClass
I want to write something like:
Dim t as Type = GetType(MyClass)
X = CreateObjectFromType(t)

is this possible?

Yes:

\\\
Dim b As Button = _
DirectCast(Activator.CreateInstance(GetType(Button)), Button)
///
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top