Delegates are like function Pointers in C++. By using delegates in C# we can call any method at run-time. There are some situations where we have to execute some method without knowing that method. That means we ask client to execute something when some condition satisfies but client should not know what method it is executing, this is possible in C# by using delegates.
Today we discuss about delegates in C# by creating simple example. Basically delegate is point to one method or list of methods which you can invoke later point of time. These methods can have parameters and return type, the declaration of the delegate purely depends method signature for which it points.
Create simple delegate example where we are logging the errors in different sources.
Open Microsoft Visual Studio => Create Console Application and name it as CreateSimpleDelegate.
Add class LogErrors to log the error as shown below.
using System;
namespace CreateSimpleDelegate
{
public delegate void LogDelegate(string sError);
class LogErrors
{
public LogDelegate SaveError(string source)
{
LogDelegate delLog;
if (source == "SQL")
{
delLog = new LogDelegate(SQLSource);
}
else
{
delLog = new LogDelegate(XMLSource);
}
return delLog;
}
private void XMLSource(string sError)
{
//save data in XML File
Console.WriteLine("XML Source to Log Errors");
}
private void SQLSource(string sError)
{
//save data in SQL Database
Console.WriteLine("SQL Data Source to Log Errors");
}
}
}
As shown above we created the delegate LogDelegate() as public. Client is calling the SaveError() method of LogErrors class by passing source variable and SaveError() method returns delegate. Based on source delegate points to different methods to save the error, but client don't know which method it is calling to save the error and client will call the method to save the error as per its wish by using Invoke() method of delegate as shown below.
using System;
namespace CreateSimpleDelegate
{
class Program
{
static void Main(string[] args)
{
LogErrors obj = new LogErrors();
LogDelegate delLog = obj.SaveError("SQL");
delLog("This is the Error");
Console.ReadLine();
}
}
}
As shown above client can call the method through delegate by using delegate Invoke() method. Run the application and the output is as shown below.
As of now we discussed the Single Cast delegate because here delegate LogDelegate is pointing to single method. If any delegate is pointing to multiple methods it is called MultiCast Delegate and we will discuss about Multicast delegates in next my articles.