C# tutorial--Delegates in C#


C# Delegates

A delegate in C# is a type that can refer to a method. The concept of delegate in C# is similar to the pointer to function in C++, but delegate in C# is said to be more safe and secure.

To use a delegate, you need to declare it first. In the following example, we declare a delegate called Mydelegate to point to a method call printName(String). The method that is referred to by the delegate must be defined in the same structure as delegate (return type, number of arguments, and types of arguments must be the same).

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

 

namespace ConsoleApplication1

{

    class Program

    {

        delegate void Mydelegate(string Name); //declare a delegate

       //with return type void and one string argument

        static void Main(string[] args)

        {

            Mydelegate  m= new Mydelegate(Program.printName);//refer to the printName method

            m("Dara Yuk"); //call the method

            Console.ReadLine();

 

        }

 

        static void printName(string Name)//declare a method with

        //return type void and one string argument to match the delegate

        {

            Console.WriteLine(Name);

        }

  }

 

}




Comments

MohitKumar comment

 MohitKumar

Check this also for C# interview questions
http://skillgun.com/csharp/interview-questions-and-answers


2014-06-10
CAPTCHA image




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.