Welcome to SpellCoder Sign in | Join | Help

Have you noticed this function in C# 2.0

This is really weird, I've been using C# 2.0 since beta 2, and I didn't notice this function in List class
Consider the following code.
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>();
for (int i = 0; i < 100; i++)
{
list.Add(i);
}
list.ForEach(delegate(int i) { Console.WriteLine(i); });
}
}

This is a simple program that creates a new List<int> and initialize it with numbers from 0 to 99.
but consider the last line, list.ForEach it takes a delegate of type Action<T> which accepts a parameter of type T, and returns nothing, so it is perfect at performing actions like printing out all the list elements or any similar action without writing the ForEach loop.
This is really similar to Ruby syntax, if you are familiar with stuff like this

>> stuff.each do |thing|
.. print thing
.. print "\n"
.. end

and it will be even better with C# 3.0 because it will be very concise consider it this way.
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>();
list.AddRange(Sequence.Range(0, 100));
list.ForEach(i => Console.WriteLine(i) );
}
}
as you can see Lambda Expressions is playing well, also the new Sequence.Range which is similar to range() method in Python

Functional Programming is coming back guys ;)
kick it on DotNetKicks.com
Digg It
Published Tuesday, October 31, 2006 5:19 AM by Mohammed Hossam
Filed Under:

Comments

# re: Have you noticed this function in C# 2.0

Tuesday, October 31, 2006 11:44 AM by JasonF
You know, you could also do the following today:

list.ForEach(Console.WriteLine);

# re: Have you noticed this function in C# 2.0

Tuesday, October 31, 2006 11:53 AM by Jemm
Yeah, I like that syntax, too.

Here is also a nice, related performance test:
http://diditwith.net/PermaLink,guid,506c0888-8c5f-40e5-9d39-a09e2ebf3a55.aspx

# re: Have you noticed this function in C# 2.0

Tuesday, October 31, 2006 4:10 PM by Tony
Why not just compile Ruby to .Net ?

http://www.plas.fit.qut.edu.au/rubynet/

# >Why not just compile Ruby to .Net ?

Tuesday, October 31, 2006 6:41 PM by lb
speeeeeed.
Anonymous comments are disabled