Creating an object using a type variable

  • Thread starter Thread starter Ramez
  • Start date Start date
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?
 
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
 
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)
///
 
Back
Top