Did you know? Delegates to extension methods

Did you know? Delegates to extension methods

  • Comments 2

I didn't know about this until recently: You can take a delegate to an extension method as if it was an instance method: http://csharpindepth.com/ViewNote.aspx?NoteID=92 The delegate's target will be set to the instance. Nice!

  • Hi, Kirill.

    This behavior is explcitly specified in the C# 3.0 Specification, 6.6 Method group conversions.

    The interesting thing (which is not specified explicitly) is that you cannot use this trick with value types or type parameters:

    using System;

    static class A

    {

       static void Foo<T>(this T x)

       {

           Action a = 1.Foo; // error CS1113

           Action b = x.Foo; // error CS1113

       }

    }

    If you try to use a type parameter, known to be a reference type, the compiler will accept it, but PEVerify will complain:

    using System;

    static class A

    {

       static void Foo<T>(this T x)

           where T : class

       {

           Action b = x.Foo;

       }

    }

  • Welcome to the forty-second issue of Community Convergence. The last few weeks have been a busy time

Page 1 of 1 (2 items)
Leave a Comment
  • Please add 4 and 6 and type the answer here:
  • Post