Gnanavel Sekar
What is Delegates and Use of Delegates in C#?
By Gnanavel Sekar in .NET on Jan 17 2017
  • Gnanavel Sekar
    Jan, 2017 17

    Basically delegates in c# are type safe objects which are used to hold reference of one or more methods in Whenever we want to create delegate methods we need to declare with delegate keyword and delegate methods signature should match exactly with the methods which we are going to hold like same return types and same parameters otherwise delegate functionality won’t work if signature not match with methods. Example public delegate int DelegateExample(int a,int b); public class Sampleclass { public int Add(int x, int y) { return x + y; } public int Sub(int x, int y) { return x - y; } } class Program { static void Main(string[] args) { Sampleclass sc=new Sampleclass(); DelegateExample delgat1 = sc.Add; int i = delgat1(5, 5); Console.WriteLine(i); DelegateExample delgat2 = sc.Sub; int j = delgat2(5, 2); Console.WriteLine(j); } } Output Add Result : 10 Sub Result : 3 Use of Delegates if we have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then we can go for delegates. Delegate's Types: 1. Single and Multi Caste Delegate

    • 1
  • Mukesh Kumar
    Aug, 2017 29

    Delegate are used to wrap the method So any one can not recognize This method is of which class

    • 0
  • Sudheshwer  Rai
    Jun, 2017 1

    Delegate is a function pointer. It holds the reference of function.Example - Suppose you have a class Vodafone. And it has 3 functions like 20rs,30rs and 40rs tariff voucher. So if you provide the object of this vodafone class then user can access all the tariff voucher. But if you will provide only a 20rs tariff voucher function reference (delegate) to the user then he can access that function. User can'nt access other tariff voucher. For more info please do practice.

    • 0
  • Emamul Hasan
    Feb, 2017 27

    Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer.

    • 0

Most Popular Job Functions