Najera
Najera

Reputation: 2879

Get generic type from string value representation in different dlls

I have 3 types all from diferent dlls y can't find how to store in a string the generic type and how to create the instance:

Type type1 = GetType1();
Type type2 = GetType2();
string strClassGenericType = "Namespace.ClassName<,>, DllName";

Type template = // How to get the generic template type?

Type genericType = template.MakeGenericType(new[] { type1, type2 });
object instance = Activator.CreateInstance(genericType);

Im not sure if this fits to my requeriment.

Upvotes: 1

Views: 270

Answers (4)

Xela
Xela

Reputation: 2382

I take it you are trying to create a type from a string value.

Try:

Type type = Type.GetType("System.String");

eg to create a textbox type from a string:

Type.GetType("System.Windows.Forms.TextBox, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

See MSDN.

Upvotes: 0

Najera
Najera

Reputation: 2879

Both vcsjones and abatishchev has a correct answer, but you miss about the dlls.

Thanks to vcsjones i used this:

string strGenericType = "Namespace.ClassName`2, DllName";
Type template = Type.GetType(strGenericType);

Type genericType = template.MakeGenericType(new[] { type1, type2 });
object instance = Activator.CreateInstance(genericType);

Thanks to abatishchev this is shorter:

string strGenericType = "Namespace.ClassName`2[[Namespace1.Type1, Type1DllName],[Namespace2.Type2, Type2DllName]], DllName";
Type genericType = Type.GetType(strGenericType);

object instance = Activator.CreateInstance(genericType);

Upvotes: 1

abatishchev
abatishchev

Reputation: 100268

The correct string representation of a generic type is like this:

"System.Collections.Generic.Dictionary`2[[System.String],[System.Object]]"

Where '2 means the number of generic type parameters.

For the fully qualified type name see the fiddle.


If you're looking for a generic type having no generic type parameters specified (so called open generic) then it's this:

"System.Collections.Generic.Dictionary`2, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"

Upvotes: 1

vcsjones
vcsjones

Reputation: 141638

In the particular case where you want the type of object that does not have it's type parameters known, you can use a backtick with the number of type parameters. Here is an example with Tuple:

Console.WriteLine(typeof (Tuple<,>).FullName); //For information only, outputs "System.Tuple`2"
var typeName = "System.Tuple`2";
var type = Type.GetType(typeName);
var generic = type.MakeGenericType(typeof (string), typeof (int));
Console.WriteLine(generic.FullName); //Outputs the type with the type parameters.

Upvotes: 2

Related Questions