The implementation of anonymous methods in C# and its consequences (part 2)

Date:August 3, 2006 / year-entry #261
Tags:code
Orig Link:https://blogs.msdn.microsoft.com/oldnewthing/20060803-00/?p=30253
Comments:    15
Summary:When the anonymous class becomes visible.

Last time we took a look at how anonymous methods are implemented. Today we'll look at a puzzle that can be solved with what we've learned. Consider the following program fragment:

using System;

class MyClass {
 delegate void DelegateA();
 delegate void DelegateB();

 static DelegateB ConvertDelegate(DelegateA d)
 {
  return (DelegateB)
   Delegate.CreateDelegate(typeof(DelegateB), d.Method);
 }

 static public void Main()
 {
  int i = 0;
  ConvertDelegate(delegate { Console.WriteLine(0); });
 }
}

The ConvertDelegate method merely converts a DelegateA to a DelegateB by creating a DelegateB with the same underlying method. Since the two delegate types use the same signature, this conversion goes off without a hitch.

But now let's make a small change to that Main function:

 static public void Main()
 {
  int i = 0;
  // one character change - 0 becomes i
  ConvertDelegate(delegate { Console.WriteLine(i); });
 }

Now the program crashes with a System.ArgumentException at the point where we try to create the DelegateB. What's going on?

First, observe that the overload of Delegate.CreateDelegate that was used is one that can only be used to create delegates from static methods. Next, note that in Test1, the anonymous method references neither its own members nor any local variables from its lexically-enclosing method. Therefore, the resulting anonymous method is a "static anonymous method of the easy type". Since the anonymous method is a static member, the use of the "static members only" overload of Delegate.CreateDelegate succeeds.

However, in Test2, the anonymous method dereferences the i variable from its lexically-enclosing method. This forces the anonymous method to be a "anonymous method of the hard type", and those anonymous methods use an anonymous instance member function of an anonymous helper class. As a result, d.Method is an instance method, and the chosen overload of Delegate.CreateDelegate throws an invalid parameter exception since it works only with static methods.

The solution is to use a different overload of Delegate.CreateDelegate, one that work with either static or instance member functions.

 DelegateB ConvertDelegate(DelegateA d)
 {
  return (DelegateB)
   Delegate.CreateDelegate(typeof(DelegateB), d.Target, d.Method);
 }

The Delegate.CreateDelegate(Type, Object, MethodInfo) overload creates a delegate for a static method if the Object parameter is null or a delegate for an instance method if the Object parameter is non-null. Hardly by coincidence, that is exactly what d.Target produces. If the original delegate is for a static method, then d.Target is null; otherwise, it is the object for which the instance method is to be invoked on.

This fix, therefore, makes the ConvertDelegate function handle conversion of delegates for either static or instance methods. Which is a good thing, because it may now be called upon to convert delegates for instance methods as well as static ones.

Okay, this time we were lucky that the hidden gotcha of anonymous methods resulted in an exception. Next time, we'll see a gotcha that merely results in incorrect behavior that will probably take you forever to track down.

Update: This behavior changed in Visual Studio 2015 with the switch to the Roslyn compiler. For performance reasons, anonymous methods are now always instance methods, even if they capture nothing.


Comments (15)
  1. Carlos says:

    It’s easier to write:

    DelegateB ConvertDelegate(DelegateA d)

    {

     return delegate { d(); };

    }

    Additionally, this also works if d is multicast.  (Note that the new delegate is a deep copy: it isn’t affected by changes to the original delegate’s invocation list.)

    The tradeoff is that it’s cheaper to create the new delegate but more expensive to call it.

  2. Grant Husbands says:

    I know it’s not the case, but shouldn’t DelegateA and DelegateB be trivially the same type, anyway?   (This is an open question – I’m not meaning to imply that you, Raymond, should know everything about every .NET design decision and I hope you don’t mind me posting an open question, here.)

    It certainly blocked me when I wanted to create a generics-based parameter-binding library, along the lines of boost::bind.

  3. Raymond wrote a really nice series of posts on this:

    Part 1

    Part 2

    Part 3

    He also points out that…

  4. You’ve been kicked (a good thing) – Trackback from DotNetKicks.com

  5. One of my favorite new features for Code Analysis in Visual Studio 2008 is our support for analyzing

  6. On the advice of Jay Wren , I decided to try our ReSharper 4.1 .  I had previously installed DevExpress

  7. On the advice of Jay Wren , I decided to try our ReSharper 4.1 .  I had previously installed DevExpress'

Comments are closed.


*DISCLAIMER: I DO NOT OWN THIS CONTENT. If you are the owner and would like it removed, please contact me. The content herein is an archived reproduction of entries from Raymond Chen's "Old New Thing" Blog (most recent link is here). It may have slight formatting modifications for consistency and to improve readability.

WHY DID I DUPLICATE THIS CONTENT HERE? Let me first say this site has never had anything to sell and has never shown ads of any kind. I have nothing monetarily to gain by duplicating content here. Because I had made my own local copy of this content throughout the years, for ease of using tools like grep, I decided to put it online after I discovered some of the original content previously and publicly available, had disappeared approximately early to mid 2019. At the same time, I present the content in an easily accessible theme-agnostic way.

The information provided by Raymond's blog is, for all practical purposes, more authoritative on Windows Development than Microsoft's own MSDN documentation and should be considered supplemental reading to that documentation. The wealth of missing details provided by this blog that Microsoft could not or did not document about Windows over the years is vital enough, many would agree an online "backup" of these details is a necessary endeavor. Specifics include:

<-- Back to Old New Thing Archive Index