Of Code and Me

Somewhere to write down all the stuff I'm going to forget and then need

Ruby’s ‘times()’ function in C# January 24, 2010

Filed under: C#,Coding,Uncategorized — Rupert Bates @ 10:20 pm

I’ve seen a lot of people enthuse about Ruby’s times() function which allows you to write code like:

5.times { |i| puts i }

which prints out:
It is a really nice syntax and it struck me that you could use similar syntax in C# by defining the following extension method on int:

public static class IntExtensions
	public static void Times(this int i, Action<int> func)
		for(int j = 0; j < i; j++)

Which then lets you write:

5.Times(i => Console.Write(i));

with the same results


One Response to “Ruby’s ‘times()’ function in C#”

  1. […] are many implementations of this in other languages, for instance Ruby’s ‘times()’ function in C# | Of Code and Me (which the WordPress.com editor fucked up as it replaced Action<int> with Action which is a […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s