Using a Delegate with Messages
Question
I'm learning about delegates and think I may have found a use for one. Basically what I have is a series of string properties that take in a minimum value and a maximum value, like so:
string weightInvalid(min as int32, max as int32)
There are several messages like this, all with unique messages but all sharing the same signature of minimum and maximum. I think that a delegate could be used here, but how would I go about doing so? It would really help me to see some code so I could get a grasp on this delegate stuff.
Solution
Below is a simple Console application example that may help...
public delegate string foo(int min, int max);
class Program
{
static void Main(string[] args)
{
CallFoo(foo1);
CallFoo(foo2);
CallFoo(foo3);
Console.WriteLine("Press ENTER to exit...");
Console.ReadLine();
}
private static void CallFoo(foo foo)
{
Console.WriteLine(foo(1, 2));
}
private static string foo1(int min, int max)
{
return "foo1";
}
private static string foo2(int min, int max)
{
return "foo2";
}
private static string foo3(int min, int max)
{
return "foo3";
}
OTHER TIPS
on c#:
delegate string weightInvalid(int min, int max);
string MyWeightInvalid(int min, int max)
{
return "";
}
string SomeMethod()
{
weightInvalid myFunc = new weightInvalid(MyWeightInvalid);
return myFunc(0, 1);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow