Hi
C# delegate pointing to different methods
A delegate can point to different methods over time.
using System;
namespace DifferentMethods
{
public delegate void NameDelegate(string msg);
public class Person
{
public string firstName;
public string secondName;
public Person(string firstName, string secondName)
{
this.firstName = firstName;
this.secondName = secondName;
}
public void ShowFirstName(string msg)
{
Console.WriteLine(msg + this.firstName);
}
public void ShowSecondName(string msg)
{
Console.WriteLine(msg + this.secondName);
}
}
class Program
{
public static void Main()
{
var per = new Person("Fabius", "Maximus");
var nDelegate = new NameDelegate(per.ShowFirstName);
nDelegate("Call 1: ");
nDelegate = new NameDelegate(per.ShowSecondName);
nDelegate("Call 2: ");
}
}
}
This delegate is used to point to two methods of the Person class. The methods are called with the delegate.
public delegate void NameDelegate(string msg);
The delegate is created with a delegate keyword. The delegate signature must match the signature of the method being called with the delegate.
var nDelegate = new NameDelegate(per.ShowFirstName);
nDelegate("Call 1: ");
We create an instance of a new delegate that points to the ShowFirstName() method. Later we call the method via the delegate.
$ dotnet run
Call 1: Fabius
Call 2: Maximus
Best Regards.
Please click the Mark as answer button and vote as helpful if this reply solves your problem.