-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Closed
Closed
Copy link
Labels
api-suggestionEarly API idea and discussion, it is NOT ready for implementationEarly API idea and discussion, it is NOT ready for implementationarea-System.Reflection
Description
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 aFunc<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 MethodDescBut 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
Labels
api-suggestionEarly API idea and discussion, it is NOT ready for implementationEarly API idea and discussion, it is NOT ready for implementationarea-System.Reflection