WoF_Angel
WoF_Angel

Reputation: 2591

C# - Use runtime-defined type as parameter in generic method

This is what i'm trying to do:

PropertyInfo[] propertyInfos = GetProperties(typeofEntity);
Type t = propertyInfos[0].GetType();
IList<t.GetType()> magicalList;

Let us say that t happens to be of type Int32, i then want the list to be

IList<Int32>

This doesn't work, as it's just the same as doing

IList<Type>

I don't want to write a dozen casts to manually find the Type.

Any Ideas? Thanks

EDIT---------------

I'm doing this because i wanto to pass an object no an NHibernate query, and automatically create the criterias corresponding to the values of the object's properties.

Ex:

Person{
public string Name
public Phone Phone 
}

Phone{
public int Number
}

I want to be able to create a person with a phone, and pass it in an nhibernate query, using DetachedFor<>. I then want to automatically create criterias for the properties of 'complex' properties of Person, such as Phone.Number.

Upvotes: 1

Views: 781

Answers (3)

Toto
Toto

Reputation: 149

There is the method System.Type.MakeGenericType wich help to create generic type passing the arguments. In your case you have the main type :

var oGenericType = typeof (IList<>);
var oSpecificType = oGenericType.MakeGenericType(typeof(int));

Upvotes: 1

JRoughan
JRoughan

Reputation: 1655

Try:

var genericType = typeof (List<>).MakeGenericType(t.GetType());
var magicalList = Activator.CreateInstance(genericType);

Upvotes: 3

SLaks
SLaks

Reputation: 888223

You can only use generics with a known type at compile-time.
In your code, the expression magicalList[0] would have no compile-time type.

You can either use a non-generic IList or do everything with reflection.

Upvotes: 4

Related Questions