Skip to content

API to change a delegate's type to a signature-compatible different delegate type #45408

@Joe4evr

Description

@Joe4evr

Background and Motivation

Inspired by a pair of comments between @GrabYourPitchforks and @jkotas at #4556 (comment)

Say that I have a Predicate<string>, but I need a Func<string, bool>. There's one kinda-hokey workaround right now:

Predicate<string> del1 = GetDelegate();
Func<string, bool> del2 = del1.Invoke; // points to Predicate<string>.Invoke's MethodDesc

But this isn't ideal since it's a hidden recursive operation: every invocation incurs an extra indirection.

Since Jan said this should be a separate API, here we are.

Proposed API

namespace System
{
    public abstract partial class Delegate
    {
        [return: NotNullIfNotNull("del")]
        public static TDelegate? ChangeType<TDelegate>(Delegate? del) where TDelegate : Delegate;
    }
}

This method is Null-in-Null-out. Exception behavior may be as follows:

  • T is an incompatible delegate type (InvalidCastException?)

Usage Examples

Predicate<string> del1 = GetDelegate();
Func<string, bool> del2 = Delegate.ChangeType<Func<string, bool>>(del1); // points to whatever MethodDesc del1 pointed to

Alternative Designs

¯\_(ツ)_/¯

Risks

None that I can think of.

History

  • Removed Try-pattern methods
  • Removed non-generic method

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions