Anonymous functions, in a simple way, are functions that can be activated directly without declaring his name, as his own name says "anonymous".
This technic works in C# projects, .NET Framework, .NET Core or WPF and can be used to reduce code, on this POST I attached a sample of using anonymous X common (regular) way.
The final result is a reduced code and fast startup.
The common way
Below is a regular code for fired Click events. To run this Form there is extra code in FormCommon.Designer.cs.
FrmCommon.cs
- using System;
- using System.Windows.Forms;
- namespace AnonymousEventsForClick
- {
- public partial class FrmCommon : Form
- {
- public FrmCommon()
- {
- InitializeComponent();
- }
- private void menu1ToolStripMenuItem_Click(object sender, EventArgs e)
- {
-
-
- var n = 0;
- APIProject.Print(++n);
- }
- private void checkBox1_CheckedChanged(object sender, EventArgs e)
- {
- APIProject.CheckStatus();
- }
- private void button1_Click(object sender, EventArgs e)
- {
-
- if (!(sender is Button)) return;
- APIProject.OpenDocument();
- }
- }
- }
FrmCommon.Desingner.cs
Extra code
...
this.menu1ToolStripMenuItem.Click += new System.EventHandler(this.menu1ToolStripMenuItem_Click);
...
this.button1.Click += new System.EventHandler(this.button1_Click);
...
this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged);
...
The Anonymous way
Below is the same code with anonymous functions to fire events, with fewer functions, lines, and usings. There is no extra code in FrmAnonymous.Designer.cs.
- using System.Windows.Forms;
- namespace AnonymousEventsForClick
- {
- public partial class FrmAnonymous : Form
- {
- public FrmAnonymous()
- {
- InitializeComponent();
- menu1ToolStripMenuItem.Click += (s, e) =>
- {
-
-
- var n = 0;
- APIProject.Print(++n);
- };
- checkBox1.CheckedChanged += (s, e) => { APIProject.CheckStatus(); };
- button1.Click += (s, e) =>
- {
-
- if (!(s is Button)) return;
- APIProject.OpenDocument();
- };
- }
- }
- }
CONCLUSION
Using this technic you can reduce code and organize it in a single place.
Anonymous functions can be used to any kind of Events, this sample shows only for the Click event.
Happy coding.