Library tutorials & articles
Events and Delegates
- Introduction
- Single Delegates
- Multi-cast Delegates
- Events
- Customized events
- Predefined events
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.
Related articles
Related discussion
-
C# video Editing/rendering
by pkuchaliya (0 replies)
-
How to Fill DataSet with more records (around 1 lakh) in a faster way
by Jayaram P (0 replies)
-
Can't print on the network with MSADESS ??
by anatha1 (2 replies)
-
Very Urgent regarding deleting the images from a folder
by Nanosteps (6 replies)
-
DataGridViewComboBoxColumn not showing values
by sachinkalse (0 replies)
Related podcasts
-
Object-Oriented Programming in Ruby
In this episode, I talk with Scott Bellware about object-oriented programming in Ruby, and Ruby's object model. This is taken from a private conversation, and the audio quality suffers at times. Much thanks to Scott for allowing this to be released.This episode of the Alt.NET Podcast is bro...
This thread is for discussions of Events and Delegates.