C# Anonymous Methods as Event Handler

As standard practice in .Net you create separate Event Handlers to handle the events of all controls on a form. In my personal code I always attempt to keep action code out of the event handlers and isolate it in its own method, this helps to keep things clean and easily altered if events change (see example below).

Example Code
        protected void Page_Load(object sender, EventArgs e)
        {
            Button1.Click += Button1_Click;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            LoadSomeData();
        }

        private void LoadSomeData()
        {
            //Do something here.
        }

Now in .Net 2.0 we are allowed to use what are called Anonymous Methods. Anonymous Methods are code blocks which can be passed as (delegate) parameters to methods accepting delegates. Anonymous Methods allow us to get ride of extra methods and the overhead they create and simply pass an Anonymous Method. Because of this new feature instead of creating a separate method as an event handler to handle the button’s click event we can simply pass the Anonymous Method as the parameter using the delegate key word. This removes that extra method and reduces our code (see example below).

Example Code:
        protected void Page_Load(object sender, EventArgs e)
        {
            Button1.Click += delegate(object sender1, EventArgs e1)
                                 {
                                     LoadSomeData();
                                 };
        }

        private void LoadSomeData()
        {
            //Do something here.
        }

This is of course an extremely simplified use of Anonymous Methods meant to be just an example of how they work, although simple it is still a valid use and may or may not help you in your code. In future posts I will attempt to show the use of Anonymous Methods in more complex scenarios but for now at least we understand what they are and how they can be used.

Published by

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s