Delegate Type Inference in C#

Today I saw some C# language syntax that made me think, "hey, wait a minute, I didn’t know you could do that!", so perhaps it’ll be new to someone else too.  Honestly, I don’t know how I missed this memo.

Let’s start off with the code, then we’ll talk about it.  I’ll including some additional lambda stuff here for the fun of it.  Sample code project:

    1 using System;

    2 using System.Threading;

    3 using System.Reflection;


    5 namespace DelegateTypeInference

    6 {

    7   class Program

    8   {

    9     static void Main(string[] args)

   10     {

   11       A(new ThreadStart(ShowTime));

   12       A(delegate { ShowTime(); });

   13       A(ShowTime);

   14       A(() => ShowTime());

   15       A(() => { ShowTime(); Console.WriteLine("boo"); });


   17       B(a => ShowTime());

   18       C((a, b) => { ShowTime(); return null; });

   19     }


   21     static void ShowTime()

   22     { Console.WriteLine(DateTime.Now); }


   24     static void A(ThreadStart t)

   25     { t(); }


   27     static void B(WaitCallback w)

   28     { w(null); }


   30     static void C(ModuleResolveEventHandler m)

   31     { Module mod = m(null, null); }

   32   }

   33 }

Look at line #11, okay, that’s been in there since C# day 1, the ability to pass a method (TinyCall) as a parameter (to function A) with a strongly typed method signature (ThreadStart).  Then in C# 2.0 one could use line #12 with the keyword delegate to create an anonymous function (no method name here, just some code). 

What I didn’t know until today is that line #13 would work, that you can just pass the method name as the parameter and the delegate type would be inferred.  Nice and easy.  Line #14/#15 was also new to me, well at least the part about using () for an empty parameter list.

Thrown in are some more C# 3.0 lambda expressions just for the heck of it.  Line #14 is an anonymous function with no return type (void), no parameters, and only one call within the function body (like line #12).  Line #15 has more than one call with the same structure.  Lines #17 & #18 are included for reference of other common lambda uses using different method signatures.


Comments (2)

  1. DanielMoth says:

    Glad to have delivered the memo 😉

  2. pkellner says:

    Nice technique (though makes my head hurt).  See you PDC?