Sdílet prostřednictvím


Do programmers really use Anonymous methods

Anonymous methods provides a  elegant way to inline callback functions (delegates). Anonymous methods typically work in the situation where you don't have significant amount of code in the callback and hence don't want to take the trouble of defining a function for it. It makes maintenance a lot easier as you don't have to jump to the definition to see what the function does.

However, do people really use it? In my day-to-day coding I rarely use them. Because I rarely have callbacks that do small things that make it a good candidate for anonymous method. In my mind anonymous methods find use in the following scenarios

  1. Event handlers
  2. Delegates that need state
  3. Function generators (for using in functional programming style coding)
  4. In Predicates/Actions/Converter delegates

However most of the event-handlers I use are UI event handlers and they are inserted by the designer which does not create anonymous methods. I don't want to get into the trouble of manually changing them. Delegates that need state are also large functions and hence not a good candidate. In production code I would rarely use a function generator so that's out too.

The last one is generally a good candidate. Consider the following code that finds an element in a collection and then prints out the entire collection (List<>) 

 List<string> nameList = new List<string>();nameList.Add("Abhinaba");nameList.Add("Kaushik");nameList.Add("Samrat");
string searchName = "Abhinaba";
// find using a Predicate<T>bool found = nameList.Exists(                    delegate (string name)  {                         return name == searchName;  } );
// Iterate using Action<T> nameList.ForEach(delegate (string str) { Debug .Print(str);} );

Especially the last usage in ForEach brings out the elegance you can achieve using anonymous method. But still I'd guess that the usage of anonymous method will be very limited in production code.