In C#, using .NET Framework 4, is there an elegant way to repeat the same action a determined number of times? For example, instead of:
int repeat = 10;
for (int i = 0; i < repeat; i++)
{
Console.WriteLine("Hello World.");
this.DoSomeStuff();
}
I would like to write something like:
Action toRepeat = () =>
{
Console.WriteLine("Hello World.");
this.DoSomeStuff();
};
toRepeat.Repeat(10);
or:
Enumerable.Repeat(10, () =>
{
Console.WriteLine("Hello World.");
this.DoSomeStuff();
});
I know I can create my own extension method for the first example, but isn't there an existent feature which makes it already possible to do this?
There is no built-in way to do this.
The reason is that C# as it is tries to enforce a divide between the functional and imperative sides of the language. C# only makes it easy to do functional programming when it is not going to produce side effects. Thus you get collection-manipulation methods like LINQ's Where
, Select
, etc., but you do not get ForEach
.1
In a similar way, what you are trying to do here is find some functional way of expressing what is essentially an imperative action. Although C# gives you the tools to do this, it does not try to make it easy for you, as doing so makes your code unclear and non-idiomatic.
1 There is a List<T>.ForEach
, but not an IEnumerable<T>.ForEach
. I would say the existence of List<T>.ForEach
is a historical artifact stemming from the framework designers not having thought through these issues around the time of .NET 2.0; the need for a clear division only became apparent in 3.0.