Skip to content

[API Proposal]: Add FieldInfo.CreateDelegate #128206

@Neme12

Description

@Neme12

Background and motivation

MethodInfo.CreateDelegate is a really useful method to get a fast method invoke function for methods obtained by reflection. I miss the same method on FieldInfo. On FieldInfo, the delegate would have to return a ref to the field to be valid.

API Proposal

namespace System.Reflection;

// Current
// public abstract class MethodInfo : MethodBase
// {
// 	public virtual Delegate CreateDelegate(Type delegateType);
// 	public virtual Delegate CreateDelegate(Type delegateType, object? target);
// 	public T CreateDelegate<T>() where T : Delegate;
// 	public T CreateDelegate<T>(object? target) where T : Delegate;
// }

// Proposed
public abstract partial class FieldInfo : MemberInfo
{
	public virtual Delegate CreateDelegate(Type delegateType);
	public virtual Delegate CreateDelegate(Type delegateType, object? target);
	public T CreateDelegate<T>() where T : Delegate;
	public T CreateDelegate<T>(object? target) where T : Delegate;
}

API Usage

static class B
{
    private string _foo;
}

static class C
{
	private static FieldInfo _fieldInfo = typeof(B).GetField("_foo", BindingFlags.NonPublic | BindingFlags.Instance)!;
	private static FooDelegate _fieldAccessor = _fieldInfo.CreateDelegate<FooDelegate>();

	// Use _fieldAccessor repeatedly to access the field value (or set it to a new value)
	// without the overhead of reflection after the initial delegate creation.

	private delegate ref string FooDelegate(B b);
}

Alternative Designs

I don't know

Risks

I don't know any

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.ReflectionuntriagedNew issue has not been triaged by the area owner

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions