How Delegates Work In C#

Most developers new to C# don't fully understand how delegates work and it's a frequently asked question on Productive C#.
 
A C# delegate is a type that represent the signature of a .NET method. A value of a delegate is effectively a method name. A delegate is similar to a C++ function pointer but it is type-safe. To define a C# delegate, you use the delegate keyword followed by a method signature. This define a type that can reference any method that match the same signature. You can create an instance of a delegate in the same way you create an instance of a type in C#. The value of a delegate is the name of the method you want to reference. It's also important to note that a delegate can point to a instance method. You can use a delegate the same way you call a method. The cool thing is that the method that a delegate reference can change at runtime. If you pass your delegate to a method, that method doesn't know what code is going to run when using the delegate. This is effectively a way to implement polymorphism without creating a hierarchy of classes. This is a more functional and .NET idiomatic way to implement the strategy design pattern.Learn more by watching the video.
 
 
A delegate allows you to implement the strategy design pattern in a more .NET idiomatic way. The code is short and compact and does not requires you to create interfaces and hierarchy of classes. Delegates provides a way to customize behavior at runtime. Starting from C# 3, the language provides a very elegant way to define methods using lambdas expressions. This increase readability of your code significantly. The .NET class libraries define generics delegates that can be used in all your applications: Action and Func. LINQ provides a vast collection of methods that accept delegates to perform many queries using a functional programming style. For an example see: SelectMany in LINQ. Delegates can be used to implement callbacks and can point to a chain of methods. Delegates are an underlying building blocks on which C# events are built upon.
 
Professional C# developers use delegates and lambda expressions every day at work. Understanding how delegate works is an essential skill for new C# developers.