C# is actually pretty good

Posted on July 29, 2007

C# 3.0 has some really good good featurs, with liberal use of generics, language integrated queries (LINQ), lamda expressions and closures, we can make it look like Ruby or some functional language:

 

public static class CommonExtensions
{
    public static Action<Action<int>> LoopTo(this int start, int end)
    {
        return new Action<Action<int>>(action => To(start, end).ForEach(i => action(i)));
    }

    public static IEnumerable<int> To(this int start, int end)
    {
        if (end < start)
            for (int i = start; i > end - 1; i–)
                yield return i;
        else
            for (int i = start; i < end + 1; i++)
                yield return i;
    }

    public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
    {
        foreach (T item in sequence) action(item);
    }

    public static void PrintLine(this object o)
    {
        Console.WriteLine(o);
    }
}

So now we could try and do this….

 

// ruby
(10..20).each { |i| puts i }
// C#
10.LoopTo(20) ( i => i.PrintLine() );

(example from BitterCoder blog)

C# 3.0
customers.Where(c => c.IsActive == true).Each(c => c.OutputToConsole());

C# 3.0
customers.Where(c => c.IsActive == true).Each(c => c.OutputToConsole());
C# 2.0
foreach(Customer c in customers)
{
if(c.IsActive)
System.Console.WriteLine(c.ToString());
}

Functional programming is dead right? ;-)

Filed Under Uncategorized |

1 Comment so far
  1. elendal July 29, 2007 11:49 pm

    Make dot and brackets optional and it would be a joy to write an embedded DSLs

Leave a Comment

If you would like to make a comment, please fill out the form below.

Name

Email

Website

Comments

For spam detection purposes, please copy the number 7754 to the field below:

© Copyright 0xDEADBEEFCAFE • Powered by Wordpress • Design by Sebastin.

free web hit counter