namespace pav.anonymousFunctions;
class Program
{
delegate string FormatNameDelegate(string LastName, bool Male, bool Doc);
static string FormatNameFn(string LastName, bool Male, bool Doc = false)
{
return Doc ? $"Dr. {LastName}" : String.Concat(Male ? "Mr." : "Ms.", LastName);
}
static void Main(string[] args)
{
FormatNameDelegate declaredFn = FormatNameFn;
Console.WriteLine(declaredFn.Invoke("Jones", true, true));
declaredFn -= FormatNameFn;
}
}
however if we have no need of removing the delegate, then we can simply reference an anonymous function to our FormatName Delegate.
namespace pav.anonymousFunctions;
class Program
{
delegate string FormatNameDelegate(string LastName, bool Male, bool Doc);
static void Main(string[] args)
{
FormatNameDelegate declaredFn = (LastName, Male, Doc) =>
Doc ? $"Dr. {LastName}" : String.Concat(Male ? "Mr." : "Ms.", LastName);
Console.WriteLine(declaredFn.Invoke("Jones", true, true));
}
}
because in the anonymous version, there is no defined FormatNameFn, there is no way to remove it from the invocation list of the declaredFn delegate.