Skip to content

Add generic overloads for MethodInfo.CreateDelegate #30800

@YairHalberstadt

Description

@YairHalberstadt

Currently usages of Delegate.CreateDelegate tend to be along these lines:

(Func<object>)Delegate.CreateDelegate(typeof(FuncObject), methodInfo)

For complicated delegates, this can be quite annoying and error prone.

it would be relatively simple to add generic overloads and it would make the API much nicer to use.

API suggestion

public partial class MethodInfo
{
    // Current
    public virtual Delegate CreateDelegate(Type delegateType);
    public virtual Delegate CreateDelegate(Type delegateType, object target);

    // New
    public T CreateDelegate<T>() where T : Delegate => (T)CreateDelegate(typeof(T));
    public T CreateDelegate<T>(object? target) where T : Delegate => (T)CreateDelegate(typeof(T), target);
}

The generic methods would not be virtual, as they're just syntactic sugar around the existing virtual.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions