C# Anonymous Methods

Anonymous Methods (C# Programming Guide)In versions of C# previous to 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduces anonymous methods. Creating anonymous methods is essentially a way to pass a code block as a delegate parameter.

An Example:

// Declare a delegate
// Declare a delegate delegate void Printer(string s); //MyOwnAnonymousMethod: delegate void TimeShouter(string a, int b); /// <summary> ///http://msdn2.microsoft.com/en-us/library/0yw3tz5k(VS.80).aspx /// </summary> class TestClass { static void Main() { // Instatiate the delegate type using an anonymous method: Printer newP = delegate(string j) { System.Console.WriteLine(j); }; // The delegate instantiation using a named method "DoWork": Printer oldP = new Printer(TestClass.DoWork); // Results from the anonymous delegate call: newP("The delegate using the new anonymous method approach is called."); // Results from the old style delegate call: oldP("The delegate using the old named method approach is called."); TimeShouter ts1 = delegate(string name, int hour) { Console.WriteLine(String.Format("{0} shouts: \"What gives? it's {1} o'clock\".", name, hour.ToString())); }; TimeShouter ts2 = delegate(string name, int hour) { Console.WriteLine(String.Format("{0} also shouts: \"What the deuce? it's already {1} o'clock\".", name, hour.ToString())); }; //And reuse the anon method in another codeblock RoundTheClock(ts1, "John"); RoundTheClock(ts2, "Paul"); } // The method associated with the named delegate: static void DoWork(string k) { Console.WriteLine(k); } static void RoundTheClock(TimeShouter ts, string name) { for (int i = 1; i < 13; i++) { ts(name, i); } } }

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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

%d bloggers like this: