Events and Delegates

Single Delegates

A delegate is called a single delegate that derives from the System.Delegate class contains an invocation list with one method. Now we will look at how the single-cast delegates are declared. In single-cast delegates, the delegate can point to both static and non-static method if both have the same signature as the delegate. Look at the code below how to declare a single-cast delegate.

public delegate void Myfunction(string,System.Int32)

The above code shows a simple delegate which will point to a method with no return type and taking two arguments as parameters. Now we see delegate that return a value.

public delegate bool MyFunctionOne();

Consider a simple example

using System;

namespace ConsoleApplication
{
   /// <summary>
   /// Summary description for Name.
   /// </summary>
   
   public class Name
   {
       public Name()
       {
           //
           // TODO: Add constructor logic here
           //
       }

       public string Compare(string NameOne, string NameTwo)
       {
           System.Int32 result=NameOne.CompareTo(NameTwo);  

           if(result==0)
           {
               return NameOne;
           }
           else
           {  
               Console.WriteLine(NameTwo +""+ NameTwo);
               return NameTwo+" "+NameOne;
           }
       }
   }
}

The above example doesn’t show the true usage of delegates but I think we are getting the idea what we want to understand. Above is a simple program which compares two strings. If the strings are equal then only one name is returned otherwise both the names are returned if the condition executes to false. Now first the main method is invoked which is situated in DelegateExample Class. In this class we have also declared our delegate.

public delegate string CompareNames(string NameOne,string  NameTwo);

It accepts two arguments of type string and also returns a string. In the main method we create the instance of Name class and then we create the instance of our delegate passing the name of our method in it as its argument so that it points to compare method now. Then we just call our delegates by passing the arguments. Which in return call the Compare method and return the string.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Java is to JavaScript what Car is to Carpet.” - Chris Heilmann