C# Delegates, Actions, Funcs, Lambdas–Keeping it super simple
Syntactic Sugar? Maybe.
[ Updated to reflect a reader’s observation – missing Func<> coverage. Now included ]
I was speaking with a colleague of mine today, Bret Stateham (https://bretstateham.com) and I was explaining my ignorance to some well established C# language constructs. I’ve always avoided language constructs that translate into “less typing.” What I mean is, delegates, actions, and lambdas can be totally avoided and you can still build the most sophisticated software. The compiler steps in at compile time and generates the IL for you (intermediate language), that language that gets translated into CPU-specific machine language at runtime by the CLR (Common language runtime).
Conceptually, and for the most part, it looks like Figure 1 below. The “Regular C# code” is probably skipped, meaning the fancy C# code ends up directly as IL. Anders Hejlsberg, the creator of C# (and the former creator of Borland’s Turbo Pascal) has spoken in detail about the inter-workings of the C# compiler in the past.
Figure 1
[ BTW, one day I’ll talk about what an amazing human being Anders is. He is the most humble, approachable, computer science genius I’ve ever met ].
Anders Hejlsberg Interview | https://www.microsoft.com/downloads/details.aspx?FamilyID=B202A125-DC9C-495A-8A5A-7BF98BECACE2&displaylang=e&displaylang=en |
Let’s start with a simple delegate example
A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented, type safe, and secure. The type of a delegate is defined by the name of the delegate.
Code is the best teacher.
Part 1 | Helps the compiler with type safety |
Part 2 | One of the methods associated with the delegate |
Part 3 | The other method associated with the delegate |
Part 4 | Our object used to demo delegates with |
Part 5 | Declare a delegate and attach a method from the demo object |
Part 6 | Declare a delegate and attach the other method from the demo object |
Part 7 | Exercise the first delegate. In other words, use it to do work. |
Part 8 | Exercise the second delegate. In other words, use it to do work. |
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ModernLanguageConstructs{ class Program { // Part 1 - Explicit declaration of a delegate (helps a compiler ensure type safety) public delegate double delegateConvertTemperature(double sourceTemp); // A sample class to play with class TemperatureConverterImp { // Part 2 - Will be attached to a delegate later in the code public double ConvertToFahrenheit(double celsius) { return (celsius * 9.0/5.0) + 32.0; } // Part 3 - Will be attached to a delegate later in the code public double ConvertToCelsius(double fahrenheit) { return (fahrenheit - 32.0) * 5.0 / 9.0; } } static void Main(string[] args) { // Part 4 - Instantiate the main object TemperatureConverterImp obj = new TemperatureConverterImp(); // Part 5 - Intantiate delegate #1 delegateConvertTemperature delConvertToFahrenheit = new delegateConvertTemperature(obj.ConvertToFahrenheit); // Part 6 - Intantiate delegate #2 delegateConvertTemperature delConvertToCelsius = new delegateConvertTemperature(obj.ConvertToCelsius); // Use delegates to accomplish work // Part 7 - delegate #1 double celsius = 0.0; double fahrenheit = delConvertToFahrenheit(celsius); string msg1 = string.Format("Celsius = {0}, Fahrenheit = {1}", celsius, fahrenheit); Console.WriteLine(msg1); // Part 8 - delegate #2 fahrenheit = 212.0; celsius = delConvertToCelsius(fahrenheit); string msg2 = string.Format("Celsius = {0}, Fahrenheit = {1}", celsius, fahrenheit); Console.WriteLine(msg2); } }} |
C# Actions – More sugar, please
You can use the Action(Of T) delegate to pass a method as a parameter without explicitly declaring a custom delegate. The sugar here is you don’t have to declare a delegate. The compiler is smart enough to figure out the proper types.
But you pay a price in terms of a limitation. The corresponding method action must not return a value. (In C#, the method must return void.)
Part 1 | The Action syntax avoids the use of a declared delegate. Everything is inline. |
Part 2 | The Action syntax avoids the use of a declared delegate. Everything is inline. |
Part 3 | Execute the corresponding Action code |
|
Func<> Delegates
This differs from Action<> in the sense that it supports parameters AND return values.
You can use this delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate.
This means that the encapsulated method must have one parameter that is passed to it by value, and that it must return a value.
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ModernLanguageConstructs{ class Program { static void Main(string[] args) { // Part 1 - First Func<> that takes an int and returns a string Func<int, string> displayHex = delegate(int intValue) { return (intValue.ToString("X")); }; // Part 2 - Second Func<> that takes a hex string and // returns an int Func<string, int> displayInteger = delegate(string hexValue) { return (int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber)); }; // Part 3 - exercise Func<> delegates Console.WriteLine(displayHex(16)); Console.WriteLine(displayInteger("10")); } }} |
Lambdas – Syntactic Sugar Squared
I’ve been staring at Lambdas for years and for whatever reason they don’t come natural to me. Maybe I need to spend more time in a functional language like F# to make them a natural construct.
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block.
The lambda expression x => x * x is read "x goes to x times x."
Part 1 | Declare 2 lambda expressions |
Part 2 | Run them. |
|
Lambdas and Queries
Lambda expressions can also be used to simplify queries.
|
Want to help?
If you’ve got some super simple examples to demonstrate advance language features, please forward them to bterkaly@microsoft.com.
The next dragon I want to slay is Dependency Injection and Inversion of Control. I want to explain these two concepts in as little code as possible. Hope you got some value out of this post.
Download for Azure SDK |
Comments
Anonymous
March 04, 2012
One intermediate piece you missed is that Func<T, U> (and its several variants) is the relative to Action<T> that provides a common, generic reusable delegate definition with a return value (the last in the list of generic type arguments). You'll notice in the Visual Studio tooltips that all of the Linq query operators use Func<T, U>.Anonymous
March 05, 2012
I got value out this post for sure! And have started to use the learnings in my blog at: http://bit.ly/zZjqi5 Thank you for this well written blog Bruno! It is exactly what I have been looking for.Anonymous
March 05, 2012
The comment has been removedAnonymous
March 05, 2012
The comment has been removedAnonymous
June 06, 2013
As long as there are limitations when debugging lambdas, I'd try balance the use that in mind.Anonymous
April 21, 2014
Great article. One question. The title says: "C# Delegates, Actions, Funcs, Lambdas–Keeping it super simple". I am experiencing it now first-hand in a new job (i.e I never used these constructs before but they use it extensively here..) saying 'Keeping it simple' Did you mean it is simpler with or without using C# Delegates, Actions, Funcs ?Anonymous
July 07, 2014
The comment has been removedAnonymous
October 30, 2014
None of this makes any sense... I just don't get code!Anonymous
December 11, 2014
In Lambdas – Syntactic Sugar Squared you used action but got a return value? Action should be Func right?Anonymous
April 26, 2015
The comment has been removedAnonymous
June 30, 2015
Its awesome post. Its very helpful. It might help to others one www.code-sample.com/.../delegates-in-aspnet-c.htmlAnonymous
December 23, 2015
I think "goes to" is a bad translation for the lambda operator. It doesn't feel like natural speech. I read lambdas as "given <lambda parameter> do <lambda method body>." So, (index) => Console.WriteLine(myArray[index]); becomes "Given index, write the value in myArray at index to the console." To me, it's MUCH easier to comprehend what's happening, and it can be expanded easily for more complex lambdas.