Posts tagged C# 3.0 extension methods ruby syntax ranges
Fun with C# Extension Methods: Easy Ranges
Dec 31st
I’m not a real Ruby on Rails developer, but I’ve tried to learn it, just to broaden my perspective. Coming from a C# background, I’m impressed by how easy it is to read Ruby code. In fact, it is usually so compact and self-descriptive, you can understand it just by reading the code. Imagine not having to write comments because your code is so clear! That’s what you can do with Ruby.
And now, using extension methods, it’s almost as easy to write C# code which is just as self-descriptive as Ruby code. I’m going to try to demonstrate that in this post.
Before we start, if you want to create your own extension methods, you need to define a static class to put them in:
public static class Extensions
I generally make my extension methods public, because I intend them to be usable for all my projects. I’m putting them all in a common project which I reference in most of my work.
Easy Ranges
.Net 3.5 includes a new extension method for IEnumerable<int> called Range. Its first parameter is the starting integer, and its second is the number of integers to count. So to get a range from 1 to 10, you write:
Enumerable.Range(1, 11)
It might be just me, but personally, I find that syntax a bit counter-intuitive. If I want the range 100 to 200, I’d have to write:
Enumerable.Range(100, 101);
Could I read that later, and easily understand what was being done? Not without a comment or two. When I read that code, it’s not obvious at all what range is being used.
But, let’s not complain. It’s easy to implement our own interpretation and extend an integer with a new method. Let’s make it more Ruby-like.
In Ruby you declare a range from 1 to 10 like this: [1..10]. A range of 100 to 200 looks like this: [100..200]. That’s nice, but pretty much impossible for us to define for C#. I think it would be just as good though if I could write something like this in my programs:
IEnumerable<int> range = 1.To(3);
For me, that compares quite nicely to the Ruby syntax. Plus, I get intellisense for the method on an integer, so it works well.
To implement that, I just have to define a new extension method like so:
public static IEnumerable<int> To(this int first, int last) { return Enumerable.Range(first, last - first + 1); }
Using this new method and the new C# LINQ syntax, I could select all even numbers from 1000 to 2000 like this:
var odds = from i in 1000.To(2000) where i % 2 == 0 select i; foreach (var i in odds) Console.WriteLine(i);
This gives 501 items, as you’d expect.
What’s next?
Ruby has a nice little syntax for defining a quick loop. Rails uses it a lot. I’m going to demonstrate how to create the same syntax in C# in my next post.