Three Cool New Features in C# C# has always had a reputation as a clean language with lots of innovation.The Whidbey-release of Visual Studio .NET ships with a new version of the C# compiler that has a number of great new features. Some of them will be implemented as generic runtime features that will show up in other languages as well, and some are truly C#-specific. All of them originated in the C# camp. In this article, I will shed some light on my three favorite new features. 1: Anonymous Methods If you have developed in C#, you are probably familiar with Delegates. Delegates are objects that encapsulate references to functions. One of the most common uses of Delegates is the implementation of event handler code. To see this in action, create a new Windows Forms (WinForms) project, and drop a button onto your form. Then, double-click on the button to create code that handles the click event. Behind the scenes, the WinForms designer creates two separate pieces of code. There is the actual event handler code, which, after adding the messagebox call, might look like this: private void button1_Click( object sender, System.EventArgs e) { MessageBox.Show("Test"); }
Additionally, and usually hidden in the form's designer-generated code region, this code is wired up to the button's click event like so: this.button1.Click += new System.EventHandler( this.button1_Click);
Note that the event handler method has to conform to a certain signature (two parameters of type object and System.EventArgs in this case). This is defined in the System.EventHandler delegate. The big question is: What did we gain by creating this separate method that is tied to the click event through the EventHandler delegate? Well, not a whole lot, because there is no true need to call the method otherwise. But all of this is necessary in order to make event handling work. Anonymous Methods simplify this a bit. Rather than instantiating a delegate and creating a method to point to, the code for the whole handler method can be created inline. No method name is defined (hence the name Anonymous Methods), but parameters are still required. Here's what that syntax looks like: this.button1.Click += delegate(object sender, EventArgs e) { MessageBox.Show("Test"); };
As you can see, what is assigned to the Click event is not a pointer to a method, but the entire method code itself including the parameters, and without a method-name. Note that there has to be a semi-colon at the end, because all of this is really just one line of code. One of the really cool uses of this technique is the ability to pass code as a parameter. Envision a scenario where a delegate is used as a call-back, a pattern that is commonly used in a number of scenarios, such as asynchronous programming, or whenever a process reports on its progress. Here is an example that illustrates this: public delegate void Feedback(string Text);
public void Execute(Feedback d1) { d1("Starting..."); // More code d1("Still going..."); // Mode code d1("Done."); }
You could now instantiate a delegate that encapsulates a method with one string parameter and pass it to the Execute method to receive feedback on the method's progress. Alternatively, you could just call the method and pass the feedback code in as a parameter: Execute( delegate(string s) {MessageBox.Show(s);} );
So everything within the parenthesis of the Execute() call is the anonymous method. And of course, you can pass in as many lines of code as you want. Oh, and before I forget, unlike manually created delegates, anonymous methods can actually see local variables defined in the calling method. So this works just fine: string s2 = "Test"; Execute( delegate(string s) {MessageBox.Show(s+s2);} );
| & | | 
By: Markus Egger Markus is the founder and publisher of CODE Magazine and EPS' President and Chief Software Architect. He is also a Microsoft RD (Regional Director) and the one of the longest (if not THE longest) running Microsoft MVPs (Most Valuable Professionals). Markus is also a renowned speaker and author.
Markus' spends most of his time writing production code. The projects Markus has worked on include efforts for some of the world's largest companies including many Fortune 500 companies. Markus has also worked as a contractor for Microsoft (including the Visual Studio team). Markus has presented at many industry events, ranging from local user groups to major events such as MS TechEd. Markus' written work has been published extensively and in magazine ranging from MSDN Magazine, to Visual Studio Magazine, and of course in Markus' own CODE Magazine and much more. Markus is a supporter of communities in North America, Europe, and sometimes even beyond.
Markus currently focuses on development in .NET (Windows, Web, Windows Phone, and WinRT) as well as Android and iOS. He is passionate about overall application architecture, SOA, user interfaces and general development productivity and building maintainable and reusable systems.
In his spare time, Markus is an avid windsurfer, scuba diver, ice hockey player and world traveler. On a rainy day, he is known to enjoy a good game on his PC or Xbox.
megger@eps-software.com | Fast Facts | | Anonymous Methods, Generics, and Partial Types are among the new features that will enter the C# arena in the near future. Some have been long anticipated; others are a surprise. All of them increase productivity and code reuse. | |
|