All the examples I can find about Func<> and Action<> are simple as in the one below where you see how they technically work but I would like
I use the Action
and Func
delegates all the time. I typically declare them with lambda syntax to save space and use them primarily to reduce the size of large methods. As I review my method, sometimes code segments that are similar will stand out. In those cases, I wrap up the similar code segments into Action
or Func
. Using the delegate reduces redundant code, give a nice signature to the code segment and can easily be promoted to a method if need be.
I used to write Delphi code and you could declare a function within a function. Action and Func accomplish this same behavior for me in c#.
Here's a sample of repositioning controls with a delegate:
private void Form1_Load(object sender, EventArgs e)
{
//adjust control positions without delegate
int left = 24;
label1.Left = left;
left += label1.Width + 24;
button1.Left = left;
left += button1.Width + 24;
checkBox1.Left = left;
left += checkBox1.Width + 24;
//adjust control positions with delegate. better
left = 24;
Action moveLeft = c =>
{
c.Left = left;
left += c.Width + 24;
};
moveLeft(label1);
moveLeft(button1);
moveLeft(checkBox1);
}