C
C
cursedgrail2017-10-11 03:38:35
Programming
cursedgrail, 2017-10-11 03:38:35

Can I add my own iteration statement in C#?

It's no secret that C# has the for iteration operator.
It is, of course, good and flexible, but there is also a problem with it: sometimes it is too cumbersome in situations where iteration is only needed from 0 to the specified index.
There was an idea: to implement your own iteration operator for cases of simple enumeration of all integers in the interval from 0 to the specified number.
That is, for example:

adfor(number/* итератор (i) изменяется от нуля до number*/)
{
    Console.WriteLine(i); /*здесь, в фигурных скобках, описывается набор действий, собственно, как и в for*/
}

adfor(number1, number2/* перегрузка, при двух аргументах, i изменятся от нуля до number1, а j - от нуля до number2*/)
{
    Console.WriteLine(i);
    {
        Console.WriteLine(j); /* в случае надобности, во вложенных фигурных скобках можно отдельно описать действия вложенного цикла*/
    }
}

Is it possible to implement something like this? Googling didn't turn up anything related to the topic.
And, yes: we need an operator that would be more convenient to use than the usual for.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2017-10-11
@yarosroman

No. You can write a function and pass numbers and a delegate to it. There is nothing cumbersome in the usual for, and there is no need for another iteration operator.
Although you can take Roslyn, make a fork, and add whatever you need to it.

S
Sergey, 2017-10-11
@sergey_kzn

What if I need not i and j, but k and m?
What if I don't need a nested loop in nested brackets, they are only used to group statements?
In my opinion, for is quite convenient.
You can use foreach and Enumerable.Range

foreach (int i in Enumerable.Range(1, 10))
{
    foreach (int j in Enumerable.Range(1, 10))
    {
        Console.WriteLine($"{i} {j}");
    }
}

If the answers do not convince you, create an issue besides Roslyn and look at the result =)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question