Search code examples
c#cilreflection.emit

DefineMethod with generic T


The type or namespace name 'T' could not be found

How can I use T in parameters?

Type[] tparams = { typeof(Expression<Func<T, object>>) };
MethodBuilder methodId = tbuilder.DefineMethod("Id", MethodAttributes.Public, typeof(IdentityPart), tparams);

Solution

  • You can use a helper method as your vehicle of filling in the type parameter. Let's assume you want T to be a class named MyVerySpecialType:

    public static class Helper
    {
        public static Type[] TypeArrayReturnerWithGeneric<T>()
        {
            return new Type[] { typeof(Expression<Func<T, object>>) };
        }
    }
    

    Then you can do:

    MethodBuilder methodId = tbuilder.DefineMethod("Id", MethodAttributes.Public, typeof(IdentityPart), Helper.TypeArrayReturnerWithGeneric<MyVerySpecialType>());