Sjoerd222888
Sjoerd222888

Reputation: 3476

Access non-generic type in C#

Let's say I have an entity of type IList<MyClass> that I want to map to a list of type IList<MyMappedClass> while keeping the same underlying collection type.

By this I mean if the instance happens to be of type List<MyClass> it should be mapped to List<MyMappedClass> and ObservableCollection<MyClass> to ObservableCollection<MyMappedClass>.

What I did so far is I can find the generic type of the list like this:

Type listType = myList.GetType(); //myList type: List<T> or ObservableCollection<T>
Type listItemType = listType.GetGenericArguments()[0];

I know that I can do this:

Type myListType = typeof(List<>).MakeGenericType(listItemType );

I cannot do that:

Type myListType = myList.GetType().MakeGenericType(listItemType );

Because it is already generic. What I am looking for is the following:

Type myListType = myList.GetType().GotNonGenericType().MakeGenericType(listItemType );

where GotNonGenericType() is a placeholder for the functionality I am looking for.

Upvotes: 3

Views: 1214

Answers (1)

lorond
lorond

Reputation: 3896

Use Type.GetGenericTypeDefinition() method. It will return a generic definition of a type, e.g. List<> from List<Whatever>. And then you can create a type with a generic arguments you want with Type.MakeGenericType(params Type[] typeArguments) method:

var list    = new List<int>();
var type    = myList.GetType();                        // ~ typeof(List<int>)
var generic = type.GetGenericTypeDefinition();         // ~ typeof(List<>)
var newType = generic.MakeGenericType(typeof(string)); // ~ typeof(List<string>)

Variable newType contains what you trying to achieve.

Upvotes: 7

Related Questions