Question: Get Type of a nested Generic class in a Generic class in C#

Question

Get Type of a nested Generic class in a Generic class in C#

Answers 2
Added at 2017-01-02 12:01
Tags
Question

In my project I use the following class: Filter<T>.Checker<U> which also has the interface IChecker. It looks like this:

class Filter<T> {

    public interface IChecker {
        ...
    }

    public class Checker<U> : IChecker {
        ...
    }

    List<IChecker> checkers;

    ...

}

The Filter class filters objects of type T. The filter uses the IChecker list to check different fields in the class T in which U is the type of this field in T.

In some other method in a different class I want to create an instance of a checker. In that method the type of T is Transaction, which is know at compile time. The type of U is only known by a Type instance. The code below show how you would normally create an instance of generic class knowing the Type.

Type type = typeof(MyObject<>).MakeGenericType(objectType);
object myObject = Activator.CreateInstance(type);

I want to take this a little bit further and do the following:

Type type = typeof(Filter<Transaction>.Checker<>).MakeGenericType(objectType);
object myObject = Activator.CreateInstance(type);

The part typeof(Filter<Transaction>.Checker<>) doesn't compile. The compiler says: Unexpected use of an unbounded generic name.

Is it possible get the type of a nested Generic class in a Generic class in C#?

Answers to

Get Type of a nested Generic class in a Generic class in C#

nr: #1 dodano: 2017-01-02 12:01

Well generics require you to specifiy all or none generic arguments. Since you don't know the second argument at compile time, you have to pass both of them as arguments to MakeGenericType:

Type type = typeof(Filter<>.Checker<>).MakeGenericType(typeof(Transaction), objectType);
object myObject = Activator.CreateInstance(type);

Although you know the type Transaction at compile time, you need to specify via typeof(), but that shouldn't hurt.

I verified via is operator that the type arguments are applied in the expected order.

nr: #2 dodano: 2017-01-02 12:01

I think you have to omit the first generic parameter T here and pass both types as an array:

Type type = typeof(Filter<>.Checker<>).MakeGenericType(typeof(Transaction),objectType);
Source Show
◀ Wstecz