Any chances to imitate times() Ruby method in C#?

Posted by Alexander Prokofyev on Stack Overflow See other posts from Stack Overflow or by Alexander Prokofyev
Published on 2008-10-07T08:01:17Z Indexed on 2010/03/15 8:59 UTC
Read the original article Hit count: 187

Filed under:
|
|
|
|

Every time I need to do something N times inside an algorithm using C# I write this code

for (int i = 0; i < N; i++)
{
    ...
}

Studying Ruby I have learned about method times() which can be used with the same semantics like this

N.times do
    ...
end

Code fragment in C# looks more complex and we should declare useless variable i.

I tried to write extension method which returns IEnumerable, but I am not satisfied with the result because again I have to declare a cycle variable i.

public static class IntExtender
{
    public static IEnumerable Times(this int times)
    {
        for (int i = 0; i < times; i++)
            yield return true;
    }
}

...

foreach (var i in 5.Times())
{
    ...
}

Is it possible using some new C# 3.0 language features to make N times cycle more elegant?

© Stack Overflow or respective owner

Related posts about c#

Related posts about ruby