Home > database >  Getting the generic Type of a generic object when only given its superclass
Getting the generic Type of a generic object when only given its superclass

Time:01-03

Suppose that we have

abstract class Parent
{

}

class Child<T> : Parent where T : CollectionBase
{

}

And some list of Parent:

List<Parent> list = new List<Parent>();

I want to be able to map Child instances like so:

// the ??? isn't relevant
Dictionary<System.Type, ???> mapping = new Dictionary<System.Type, ???>();

void Add<T>(Child<T> child) where T : CollectionBase
{
    mapping[typeof(T)] = ???;
}

This works fine.

But now imagine that you're given an object of apparent type Parent, but you know that its actual type is Child<T> (except that you don't know which T).

Is there any way to determine the T so that you're able to retrieve the corresponding mapping?

It is simple enough to workaround this by storing key information in other ways, but I'm mostly just curious.

CodePudding user response:

you can use reflection to get the actual type T, Is it what you want?

abstract class Parent { }

class Child<T> : Parent where T : CollectionBase { }

public class CollectionClass : CollectionBase { }

get generic type:

Parent p = new Child<CollectionClass>();

Type x = p.GetType().GenericTypeArguments.FirstOrDefault(); // the x will be tyepof(CollectionClass)
var isEqual = x == typeof(CollectionClass); // isEqual will be true

CodePudding user response:

Here's a simplified version of what you're asking:

void Main()
{
    Parent instance = new Child<string>();
    Type firstGenericTypeArgument = instance.GetType().GenericTypeArguments.First();
    Console.WriteLine(firstGenericTypeArgument == typeof(string));
}

abstract class Parent { }

class Child<T> : Parent { }

That produces True, so firstGenericTypeArgument is the same as typeof(string) in this example.

  • Related