During one of my lab sessions I was given a problem related to delegates which I solved as belows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelegateApp
{
delegate void GreeterDelegate();
class Program
{
static void GreetGoodMorning()
{
if (DateTime.Now.ToString().EndsWith("AM"))
Console.WriteLine("Good Morning!");
}
static void GreetGoodEvening()
{
if (DateTime.Now.ToString().EndsWith("PM"))
Console.WriteLine("Good Evening!");
}
static void Main(string[] args)
{
GreeterDelegate Greeters = new GreeterDelegate(GreetGoodMorning);
Greeters += GreetGoodEvening;
Greeters();
Console.ReadLine();
}
}
}
What I did was that I used the conditions to check time inside the methods. But one of the Lab Faculty suggested me to do this either:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelegateApp
{
delegate void GreeterDelegate();
class Program
{
static void GreetGoodMorning()
{
Console.WriteLine("Good Morning!");
}
static void GreetGoodEvening()
{
Console.WriteLine("Good Evening!");
}
static void Main(string[] args)
{
GreeterDelegate Greeters;
if (DateTime.Now.ToString().EndsWith("AM"))
Greeters = new GreeterDelegate(GreetGoodMorning);
else
Greeters = new GreeterDelegate(GreetGoodEvening);
Greeters();
Console.ReadLine();
}
}
}
He suggested to move the conditions out from the methods into the Main() method. The End result is the same but I am still confused about which way is the better way to do it especially considering the use of delegates in large programs, whether the conditional check should be moved into the methods or should be kept outside.
Neither of them is good code. These are just constructed samples to show the syntax and usage of delegates. In this sample you wouldn’t need a delegate at all, because it is just a normal call to a function.
Delegates are useful under the following conditions:
The two samples don’t have the same meaning. I would prefer the first version because it does what it says. GreetGoodMorning checks whether it’s morning or not and doesn’t do anything when it isn’t. I would rewrite the 2nd version into the following:
Nobody should write any code just to use a delegate.