Delegate for generic class and method with generic return type

is_oz

When using delegate with generic classes, have an issue. Class is generic but method is not. However method return type is generic type.

public abstract class BaseEntity {
    public DateTime CreateDateTime { get; set; } = DateTime.Now;
    public long CreateUserId { get; set; }
}

public class ClassA : BaseEntity {

}

class Program {
    private delegate object MyDelegate(long id);
    private static MyDelegate _myHandler;

    static void Main(string[] args) {
        var genericType = typeof(TestClass<>).MakeGenericType(typeof(ClassA));
        var createMethod = genericType.GetMethod("CreateEntity");
        _myHandler = (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), null, createMethod);

        var result = _myHandler(5);
    }
}

class TestClass<T> where T : BaseEntity, new() {
    public T CreateEntity(long userId) {
        return new T() { CreateUserId = userId };
    }
}

This code throw exception.

Update 1: Fix the code to be understandable.

Exception:

An unhandled exception of type 'System.NullReferenceException' occurred in Unknown Module.
Object reference not set to an instance of an object. occurred
John

The issue is here:

_myHandler = (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), null, createMethod);

The second parameter of the overload of .CreateDelegate you're using takes an instance of the type to which the method belongs.

You should either make your method static, or create an instance of genericType:

var instance = Activator.CreateInstance(genericType);
_myHandler = (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), instance, createMethod);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related