How to create an instance of a class from a variable?

T

teel

Hi there,
I need to create an instance of a class whose name I have in a string
variable, let's say that:
string myTypeName = "MyType";

and in a result I need the equivalent of:
MyType obj = new MyType();

I've tried something like Type.GetType which returns the System.Type
but I don't know how to create a new object with this. My .NET version
is 1.1

I'd be grateful for help.

Best regards
teel
 
M

Marc Gravell

Activator.CreateInstance(type)
or
type.GetConstructor(Type.EmptyTypes).Invoke(null)

(or a range of similar)

*However* note that you will only normally be able to use "object" as
the receiving variable. You can get around this by casting to
base-classes and interfaces if you know that the concrete type will
(at runtime) support it, e.g.

using System;
using System.Windows.Forms;

public interface IMyInterface { void SomeMethod();}

public class MyClass : IMyInterface {
public void SomeMethod() {
MessageBox.Show("Hi");
}
}
static class Program {
static void Main() {
Type type = Type.GetType("MyClass");
IMyInterface i = (IMyInterface)Activator.CreateInstance(type);
i.SomeMethod();
}
}

Marc
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,


teel said:
Hi there,
I need to create an instance of a class whose name I have in a string
variable, let's say that:
string myTypeName = "MyType";

and in a result I need the equivalent of:
MyType obj = new MyType();

I've tried something like Type.GetType which returns the System.Type
but I don't know how to create a new object with this. My .NET version
is 1.1

I'd be grateful for help.

Take a look at the different CreateInstance method available from Assembly
and AppDomain classes.
 
R

RobinS

He's trolling. He's been doing this kind of crap in the VB.Net newsgroup
for quite a while.

Robin S.
 
P

pfc_sadr

C# does not support multi-inheritence

..NET has no tangible benefit over VB and C++ is for fags

so until .NET supports multiple inheritence, classes are POINTLESS
 
P

pfc_sadr

CLASSES ARE POINTLESS DIPSHIT

THEY MAKE YOUR CODE RUN SLOWER AND MORE VERBOSE

ONLY A ****ING RETARD WOULD USE C#


YOU ARE CRIPPLED BY CLASSES, KIDS
 

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