C#

Introduction to Delegates in C#

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at detailed Introduction to Delegates in C#. It's our 21st tutorial in C# series and now we are entering in the complex field. C# concepts, we have studied so far, were quite simple, but now we are slowly moving towards complex topics. Delegates are not that difficult as normally considered, you just need to understand its basic idea and rest is quite simple. So, let's get started with Introduction to Delegates in C#:

Introduction to Delegates in C#

  • Delegates in C#, created by using delegate keyword, are used as a type safe pointer, normally pointing towards C# Methods & Events.
  • The signature of the Delegate & the function ( its pointing to ) must be same.
  • As Delegate is a reference type Data type, so we can create its new instance.
  • If you want to use any Method as a variable, then Delegates are literally the answer. ( We will have a look at it shortly )
  • Delegates belong to builtin C# class named System.Delegate.
  • Let's have a look at it's syntax:
  • You can see in above figure that I have first declared the delegate, outside the class and I have used delegate keyword in its definition.
  • Now in the Main function, I have created a new instance of this Delegate and in its constructor, I have pointed out the Method Name, to which I want to assign this delegate.
  • After that I have invoked the Method using Delegate, instead of the Method's name itself.
  • You need to make sure that signature of this delegate & the function must be same, when I use the word signature then that means return type and parameters.
  • My Function & delegate, both have void return type, so if I change return type of any one of them, then compiler will generate an error and that's why we call it type safe.
  • Similarly, the number & type of Function Parameters must have to be same for both Delegate & its pointed Method.
  • Let's have a look at MultiCast Delegate in C#:

MultiCast Delegate in C#

  • We can assign / point a single delegate to multiple Methods / Functions, such delegates are called MultiCast Delegates in C#.
  • In the below figure, I have assigned a single delegate to 3 methods and when I invoked the delegate then it has executed all these 3 methods.
  • In the above figure, I have used two ways to chain delegates together, in the first way I have used plus sign ( + ), while in second one I have used append sign ( += ).
  • You must be wondering why to use these function pointers when we can directly invoke the Method using its own name.
  • So, in order to understand the importance of delegates, let's design a simple example:

Example of Delegate in C#

  • Let's create simple code, where we create a new class named StudentsData and it will have 3 C# Properties and 1 C# Method.
  • You can see this code in below figure and I have placed an if loop in my method which has a Boolean expression in it i.e. score < 40.
  • This condition Score < 40 is hard coded in my method, which makes my code quite rigid, whereas its always good practice to add flexibility in your code so that you could reuse it.
  • So, now let's create a new method and add a delegate instead of this Boolean expression and as its a Boolean expression, so my delegate also has to be of Boolean return type.
  • You can see in above figure that I have created a delegate named StudentsDelegate, which is of Boolean return type.
  • After that, I have created a method in Main Function named CheckStatus, which is also of Boolean Type and taking Score as a parameter.
  • If you look closely, the signature of this delegate & method CheckStatus are same.
  • I have used the delegate to point to this method CheckStatus and have placed our failed condition in it.
  • Now this function will return either TRUE or FALSE i.e. it's kind of a Boolean expression.
  • Finally, I have added a delegate as a second parameter in FailedStudents Function, and then used this parameter as a condition in IF Loop.
  • So, now my class is completely flexible, if I wanna change the condition, then I don't need to change the class, I can change score condition in my Main class.
  • Now, you must be thinking, we have done so much coding just to shift a condition from one class to another, we have done it for a purpose.
  • So, let's have a look at the below image, where I have used Lambda Expression in C#:
  • In C#, we can use lambda expressions, which we will study in coming lectures, but for now you can see in above figure that I have removed the delegate instantiation and have also removed the pointed method.
  • Instead I have just placed a Lambda expression and visual studio has created the delegate & method in the background, which we don't need to worry about.
  • We just need to understand this lambda expression where we have placed our condition i.e. Score < 40.
  • Delegates are the basis of this lambda expression, which is quite handy, it has not only made the class flexible but have also reduced the code to just single line.
So, that was all about Delegates in C# and I hope you have understood their importance. In the coming lecture, we will have a look at Exception Handling in C#. Till then take care & have fun !!! :)


JLCPCB – Prototype 10 PCBs for $2 (For Any Color)

China’s Largest PCB Prototype Enterprise, 600,000+ Customers & 10,000+ Online Orders Daily
How to Get PCB Cash Coupon from JLCPCB: https://bit.ly/2GMCH9w

Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir