Skip to content

Proposal: Support delegate signature equivalence #4331

Closed

Description

@HaloFour

See Roslyn: Convert delegate types with compatible signature automatically

Currently the various CLR compilers do not permit treating one delegate of a specific signature as the same as another delegate of an identical signature. The compilers that do (VB.NET) do so by wrapping the existing delegate instance with the new delegate which incurs a performance penalty at the time of invocation.

It appears that for whatever reason, accidentally or otherwise, the CLR/JIT have no real issue using one delegate in place of another. The verifier does complain that an unexpected type is on the stack for the specified call but otherwise the program does execute.

I propose that the verifier be modified that if the type expected and the type on the stack are different but are both delegate types, and that the Invoke method on both delegates share the same signature that the verifier allow the operation.

This would permit delegates of identical signatures to be considered equivalent without the performance penalty either at the time of conversion or the time of invocation.

Activity

  1. masonwheeler commented on Jun 25, 2015

    @masonwheeler
    Contributor

    I think this is definitely worth doing. The purpose of verification is to prove that type safety will not be violated. If you can prove that all types involved in the delegate are equivalent, then type safety will not be violated, so there's no reason to report it as problematic.

  2. HaloFour commented on Jun 25, 2015

    @HaloFour
    Author

    To note, this is not without type-safety issues. While the CLR will happily invoke the delegate it is not recognized as that type. For example:

    public static boolean Test(Predicate<string> predicate) {
        object obj = predicate;
        boolean isPredicate = (obj is Predicate<string>);  // false!
        predicate = (Predicate<string>) obj;  // InvalidCastException!
    
        return predicate("Foo!");
    }
    
    Func<string, bool> predicate = () => true;
    Test(predicate); // assuming compiler allowed this and running full-trust

    Understandably that might make this problematic, but I'd love to at least use this proposal as a starting point to perhaps discuss delegate signature equivalence either through the CLR directly or perhaps with efficient conversion methods in the BCL.

  3. masonwheeler commented on Jun 25, 2015

    @masonwheeler
    Contributor

    @HaloFour Interesting point, but I have to wonder how relevant it is. I don't believe I've ever seen code that takes a variable of formal type X and applies an is operator, an as cast, or a hard cast on that variable using type X, and I can't imagine a scenario in which I would want to do so.

  4. iskiselev commented on Jun 26, 2015

    @iskiselev

    There is one more small problem - current implementation of Delegate.Combine will throw an exception if delegates of different types passed to it, even if their types are compatible.

  5. masonwheeler commented on Jun 26, 2015

    @masonwheeler
    Contributor

    @iskiselev This appears to be based on a runtime-level (C++) method called IsEquivalentTo, and there's a mechanism in place for determining equivalence of non-identical types.

    That actually brings up an interesting idea: it implies that this whole thing could be implemented fairly simply by defining IsEquivalentTo for delegate types. Put all the logic there, in one centralized location, and then let compilers and PEVerify call IsEquivalentTo.

    ...maybe. Probably not the compiler, because the Type isn't created yet at the point where it needs to verify this. Not sure how PEVerify works under the hood, but hopefully it would be able to leverage this.

    Good catch! :)

  6. transferred this issue fromdotnet/coreclron Jan 30, 2020
  7. added this to the Future milestone on Jan 30, 2020
  8. dmitriyse commented on Apr 8, 2020

    @dmitriyse

    Do we have some progress on this feature?
    In BCL itself and in a huge amount of other libs we can find a code like this:

        if (obj is Action){ ... }
        else if (obj is Task) { .... }

    if inside the obj is any non Action delegate like delegate void MyAction(), this code will be broken.

    Approaches:

    • make is, as and cast operator behave especially for delegates with equivalent signature (still problem with obj.Type.Name == "Action" code)
    • Special Annotation and a compiler suport
    // The same annotation technique as for "Nullable" or "Dynamic" for generics support.
    public class SupportEquivalenceAttribute: Attribute
    {
    }
    
    // C# syntax
    public void MyNewMethod(var Action a)
    {
       ....
    }
    
    // IL representation:
    public void MyNewMethod([SupportEquivalence]Action a)
    {
            if (a.Type.Name == "Action") // Compiler warning or error, because "a" could contain a different type of delegate
            {
            }
            if (Delegate.IsEquivalent<Action>(a)) // Correct implementation
            {
            }       
    }
    
    public void MyOldMethod(Action a)
    {
           
    }
    
    delegate void MyAction();
    public void MyCode()
    {
        MyAction action = ()=>Console.WriteLine("HelloWorld");
        MyOldMethod(action); // Compiler Error!
        MyNewMethod(action) // Works, as implementation of MyNewMethod declares that it's support "Delegate equivalence feature".
    }
  9. dotnet-policy-service commented on Oct 8, 2024

    @dotnet-policy-service
    Contributor

    Due to lack of recent activity, this issue has been marked as a candidate for backlog cleanup. It will be closed if no further activity occurs within 14 more days. Any new comment (by anyone, not necessarily the author) will undo this process.

    This process is part of our issue cleanup automation.

  10. added
    backlog-cleanup-candidate
    on Oct 8, 2024
  11. dotnet-policy-service commented on Oct 23, 2024

    @dotnet-policy-service
    Contributor

    This issue will now be closed since it had been marked no-recent-activity but received no further activity in the past 14 days. It is still possible to reopen or comment on the issue, but please note that the issue will be locked if it remains inactive for another 30 days.

  12. removed this from the Future milestone on Oct 23, 2024
  13. locked and limited conversation to collaborators on Nov 22, 2024
  14. removed
    backlog-cleanup-candidate
    on Nov 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions