Creating Generic object at runtime

K

kumar.senthil

Hi,
I would like to know whether we can create a generic object at
runtime using the type obtained using reflection.

Type myType = Type.GetType("Namespace.Class");
MyClass<myType> test1 = new MyClass<myType>();

Basically, i need to create the generic object at run time and the
type is decided at runtime.

Thanks,
Senthil
 
J

Joanna Carter [TeamB]

<[email protected]> a écrit dans le message de (e-mail address removed)...

| I would like to know whether we can create a generic object at
| runtime using the type obtained using reflection.
|
| Type myType = Type.GetType("Namespace.Class");
| MyClass<myType> test1 = new MyClass<myType>();
|
| Basically, i need to create the generic object at run time and the
| type is decided at runtime.

Certainly, you need to use Type.MakeGenericType in C# 2.0, this replaces a
..NET 1.0 method that is deprecated and that I can't remember the name of.

{
Type myType = Type.GetType("Namespace.Class");

Type[] typeArgs = new Type[] { myType };

Type typeToCreate = typeof(MyClass<>).MakeGenericType(typeArgs);

MyClass test1 = (MyClass) Activator.CreateInstance(typeToCreate,
typeArgs);
}

Joanna
 
N

Nicholas Paldino [.NET/C# MVP]

Joanna,

MakeGenericType doesn't replace anything in .NET 1.0 because it never
existed in .NET 1.0.
 
J

Joanna Carter [TeamB]

"Nicholas Paldino [.NET/C# MVP]" <[email protected]> a écrit
dans le message de [email protected]...

| MakeGenericType doesn't replace anything in .NET 1.0 because it never
| existed in .NET 1.0.

Aaahh ! Brain fart :))

I think I meant beta 1 of the .NET 2 framework.

<puts tail between legs>

Joanna
 

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