Extending the int type to have a For method
It’s been months since I had anything interesting to blog about. Mostly because I was working away on some new stuff I couldn’t talk about. Anyway, now I feel like blogging again.
I’m working on an Azure Worker Role which processes messages from an Azure Queue. In the main loop of my Worker Role, I had a piece of code like this:
var messageCount = cloudQueue.RetrieveApproximateMessageCount();
for (var i = 0; i < messageCount; i++)
{
ThreadPool.QueueUserWorkItem(ProcessQueueMessage);
}
Simple enough: Retrieve the approximate message count and queue up enough work items to process the messages.
Then I thought, “I’m sick of writing stupid for loops!”
So I extended the int type with the following extension method:
/// <summary>
/// Extends int to have a For method.
/// </summary>
/// <param name="value">The int being extended.</param>
/// <param name="action">The Action to execute.</param>
public static void For(this int value, Action action)
{
for (var i = 0; i < value; i++)
{
action();
}
}
Now, I can write that loop in a single line of code:
cloudQueue.RetrieveApproximateMessageCount().For(() => ThreadPool.QueueUserWorkItem(this.ProcessQueueMessage));
Which is nice! Love it.
Then I thought, “What if I need to know the ordinal value of the for loop inside the action, though?”
So I extended the int type with another extension method:
/// <summary>
/// Extends int to have a For method.
/// </summary>
/// <param name="value">The int being extended.</param>
/// <param name="action">The Action<int> to execute.</param>
public static void For(this int value, Action<int> action)
{
for (var i = 0; i < value; i++)
{
action(i);
}
}
So now, I can write:
10.For(i => Console.WriteLine(String.Format("Writing {0}", i)));
And see the following output:
Writing 0
Writing 1
Writing 2
Writing 3
Writing 4
Writing 5
Writing 6
Writing 7
Writing 8
Writing 9
Of course, I’ll want the same extensions for long, etc. That’ll be simple enough…
Best,
Brian
Comments
- Anonymous
January 06, 2010
I was looking for this a while ago and came across these 2 implementations:http://stevenharman.net/blog/archive/2008/02/12/ruby-has-ranges-and-so-does-c.aspxhttp://www.curtismitchell.com/2b/?p=52What do you think? Yours seems simpler. - Anonymous
January 06, 2010
@barnaby Interesting. Curtis' approach turns an int into a Enumerable<int>, yielding out the ints. I think my approach is simpler for the use for which I intended it, but I like his, too.