Introduction to Delegates in C#

In this article we will explain the concept of Delegates and how to use them in C#.

Definition of Delegates:

Delegate is an abstract concept used since the first version of .NET Framework. A delegate is a reference type variable that points the reference to a method. All delegates are derived from System.Delegate class. For example in Windows Forms or WPF, a method event works with the concept of delegates.

Declaration of Delegates:

To declare a delegate in C# we use the key word Delegate followed by the signature of the method. The name of the delegate is the same of the method indicated in the signature. We can also use visibility indicators in the beginning such Public, Private, Protected. So this is the syntax of delegate declaration:

delegate <return type> <delegate-name> <parameter list>

For example:

public delegate string TestDelegate (int i);

The above delegate can be used to reference any method that has an integer parameter and returns a string variable.

How to use Delegates:

 After declaring a delegate, we create an object delegate with new key word. The following example explains how to declare and instantiate and use of above declared delegate.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        //Delegate declaration
        public delegate string TestDelegate(int i);

        static string n = null;

        public static string TestMethod(int j)
        {
            n = Convert.ToString(j);
            return n;
        }

        public static string getValue()
        {
            return n;
        }

        static void Main(string[] args)
        {
            //delegate instantiation
            TestDelegate d1 = new TestDelegate(TestMethod);

            //calling method using delegate objects
            d1(10);
            Console.WriteLine("The returned value is: {0}",getValue());
            Console.ReadKey();
        }
    }
}


The result is 10.

delegate in c#

So let's explain the above code:
- We declared a delegate TestDelegate that refers to a method having an integer paramater and returning a string value.
- And we declared a string n.
- After that we declared a method TestMethod with an integer parameter j and returns a string value, this method convert an integer value to string.
- Also we declared a method getVlue that returns a string value.
- In the Main void we instantiated the TestDelegate d1 and we called TestMethod using d1.
- Then we displayed the returned value with getValue method.

Introduction to Delegates in C# Introduction to Delegates in C# Reviewed by Bloggeur DZ on 02:46 Rating: 5

Aucun commentaire:

Fourni par Blogger.