is_oz
is_oz

Reputation: 993

Delegate for generic class and method with generic return type

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

Upvotes: 3

Views: 229

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38795

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);

Upvotes: 3

Related Questions