Delegates in C#

By Feb 03, 2017

Description:

In this article, we explain what are delegates in Csharp and how to use them to pass methods as arguments. We illustrate their use with several examples.

Preferencesoft

A delegate is a class, parameterized by a function prototype, such that any instance of this class, pertaining to a certain function prototype, allows to reference any method with the same signature as specified.

References to one or more methods can be added to a delegate instance.

To compare with the C++ language, a delegate instance is like a pointer to a function of a certain signature.

In this article, we will see what is the usefulness of a delegate, how to declare and instantiate delegate and give examples.

Usefulness of a delegate

Often, to illustrate the use of a delegate, we declare a delegate object, attach a method to this instance, then we call it. Per one such example, we can have the impression that a delegate is used to invoke a method.

In fact, delegates essentially allow to pass methods as parameters.

Delegates facilitate implantation of callback functions. In addition, delegates form the basis of event handling in C#.

Declaring and Instantiating Delegates

Syntax for delegate declaration is:

delegate <return_type> <delegate_name>(<parameter list>);

By example, if we want to reference functions that take a string parameter and return a Boolean, we declare a delegate MyDelegate like follows:

public delegate bool MyDelegate(string s);

Declare a method with the same signature:

public static bool AMethod(string str)
{
    return str.Length >= 10;
}

The delegate MyDelegate can be used to reference the method AMethod

static void Main(string[] args)
{
    MyDelegate md = new MyDelegate(AMethod);
    Console.WriteLine(md("0123456789A"));
}

The MyDelegate instance md refers to the method AMethod and the statement md("0123456789A") invokes the method. At runtime, the program displays true.

Examples

Here is a program which uses a delegate to display information about different people in two ways.

public delegate void PrintDelegate(string s);

        public static void Print(string str)
        {
            Console.WriteLine(str);
        }

        public static void UPrint(string str)
        {
            string uline = new String('=', str.Length);
            Console.WriteLine(uline);
            Console.WriteLine(str);
            Console.WriteLine(uline);
        }
        class Person
        {
            int age;
            string name;

            public Person(string n, int a)
            {
                age = a;
                name = n;
            }

            public void PrintPerson(PrintDelegate printer)
            {
                printer("My name is " + name + ", and I am " + age);
            }
        }
        static void Main(string[] args)
        {
            Person P1 = new Person("John", 20);
            Person P2 = new Person("Harry", 35);

            P1.PrintPerson(UPrint);
            Console.WriteLine();
            P1.PrintPerson(Print);
            Console.WriteLine();
            P2.PrintPerson(UPrint);
        }

This program generates terms of simple recurrent sequences, providing lambda expression to the method Generate. This lambda expression is compatible with the FuncDelegate  delegate.

       public delegate double FuncDelegate(double d);

        class Sequence
        {
            public List<Double> Generate(FuncDelegate func, int n, double u0)
            {
                List<Double> element = new List<Double>();
                double u = u0;
                for (int i=0; i<n; i++)
                {
                    element.Add(u);
                    u = func(u);
                }
                return element;
            }
        }
   	static void Main(string[] args)
        {
            Sequence seq = new Sequence();
            List<double> dlist = seq.Generate(x => x + 1, 50, 1.2);
            for (int i = 0; i < 50; i++)
            {
                Console.WriteLine(dlist[i]);
            }
            dlist = seq.Generate(x => x * x, 50, 2);
            for (int i = 0; i < 50; i++)
            {
                Console.WriteLine(dlist[i]);
            }
        }

In this example, we sort a list of words by length. We use the LINQ library and a lambda expression as a delegate.

string[] words = { "mlkj", "popp", "mnop", "aa", "ga", "window", "ca", "cdef", "b", "a", "abc", "c", "system", "application" };
var list = words.ToList();
list.Sort((w1, w2) => w1.Length - w2.Length);
foreach (string s in list)
{
    Console.WriteLine(s);
}

Output

b
a
c
aa
ga
ca
abc
mlkj
popp
mnop
cdef
window
system
application


CSharp

Categories

Share

Follow


KodFor Privacy Policy