title: C# extension method for a method group
body: <p>I want to implement an extension method for a method. Consider the following code sample (<a href="http://dotnetfiddle.net/HztiOo" rel="noreferrer">http://dotnetfiddle.net/HztiOo</a>) :</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  
  public class Program
  {
      public static void Main()
      {
          A a = new A();
          // Noticed that Next() is called twice
          Console.WriteLine(a.Next(1));
          Console.WriteLine(a.Next(1));
  
          // Works
          var withCache = ((Func&lt;int,int&gt;)a.Next).AddCaching();
          withCache = new Func&lt;int,int&gt;(a.Next).AddCaching();
          withCache = ExtensionMethods.AddCaching&lt;int,int&gt;(a.Next);
  
          // Doesn't work :(
          // withCache = a.Next.AddCaching&lt;int,int&gt;();
          // Func&lt;int,int&gt; withCache = a.Next.AddCaching();
  
          // Notice that Next() is only called once
          Console.WriteLine(withCache(1));
          Console.WriteLine(withCache(1));
      }
  }
  
  public class A
  {
      public int Next(int n)
      {
          Console.WriteLine("Called Next("+n+")");
          return n + 1;
      }
  }
  
  public static class ExtensionMethods
  {
      public static Func&lt;TKey,TVal&gt; AddCaching&lt;TKey,TVal&gt;(this Func&lt;TKey,TVal&gt; fetcher)
      {
          var cache = new Dictionary&lt;TKey, TVal&gt;();
          return k =&gt;
          {
              if (!cache.ContainsKey(k)) cache[k] = fetcher(k);
              return cache[k];
          };
      }
  }
  </code></pre>
  
  <p>I would like to be able to call the extension method without an explicit cast. In both "doesn't work" examples above, the type system should be able to figure out which overload to use on its own...</p>
  
  <p>Why can't I just use <code>a.Next.AddCaching&lt;int,int&gt;()</code> ?</p>
  
  <p>Note: this is just an example, I am not interested in discussing the best way to add a cache to a method invocation, as there are many other possibilities for this kind of extensions.</p>