Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate for generic class and method with generic return type

Tags:

c#

delegates

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
like image 693
is_oz Avatar asked Jun 14 '26 20:06

is_oz


1 Answers

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);
like image 79
DiplomacyNotWar Avatar answered Jun 16 '26 09:06

DiplomacyNotWar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!