C# Anonymous methods, lambda expressions and Ruby
In my last post I had discussed about anonymous methods.
I had used the following code snippet to show how anonymous methods can be used to print out a List<string>
List<string> nameList = new List<string>();nameList.Add("Abhinaba");nameList.Add("Kaushik");nameList.Add("Samrat");
nameList.ForEach(delegate (string str) { Debug.Print(str);});
jeswin's comment on that post was "the ugliness is really apparent at the callsite ... Once we see lambdas and automatic type inference in C# 3.0, a lot of people will start using it. With LINQ, at least this is as concise as Ruby. "
He hit my sweet spot about Ruby and how languages like C# are poaching into its domain. Lets see how I'd code this is Ruby
$nameList = [ "abhinaba", "kaushik", "samrat" ]
$nameList.each { | str | puts str }
This is concise and intuitive as for each element run this block of code. But with C#3.0 (LINQ) coming up, this can also be done as concisely with the usage of lambda expressions. The following code is valid C# 3.0
List<string> nameList = new List<string>{ "abhinaba", "samrat", "kaushik" };nameList.ForEach(str => Console.WriteLine(str) );
So the ugly delegates and explicit type parameters have gone away. This is concise but is it really understandable by C#'s target audience?
One more interesting thing about the code is the first line where I was able to initialize the collection by directly passing the elements using the C# 3.0 Collection Initializer.
However, I am not a great fan of adding language features like this in C#. Every language has a style and a target audience and I don't think dynamic/functional programming concepts creeping into C# is a healthy trend.