Is there a reason to use this:
bool flag;
public Form1()
{
if (flag) byDelegate = square;
else byDelegate = cube;
Text = byDelegate(3).ToString();
}
int square(int i) { return i * i; }
int cube(int i) { return i * i * i; }
delegate int delegate1(int x);
delegate1 byDelegate;
Rather than:
bool flag;
public Form2()
{
Text = fakeDelegate(3).ToString();
}
int square(int i) { return i * i; }
int cube(int i) { return i * i * i; }
int fakeDelegate(int i)
{
if (flag) return square(i);
else return cube(i);
}
Thanks.
Delegates are usually used asynchronously, for events or passed into methods/types so that the method the delegate points to (‘function pointers’) can be called later. In your case there looks like there’s no advantage as you’re doing everything synchronously.
For example
You generally don’t need to declare your own delegates in 3.5 upwards unless you want to your code to provide a bit more meaning via those declarations. The
Actiontype and theFunctype (func provides a method with a return value) save you the effort.