Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerable giving unexpected output

class Foo
{
    public static IEnumerable<int> Range(int start, int end)
    {
        return Enumerable.Range(start, end);
    }

    public static void PrintRange(IEnumerable<int> r)
    {
        foreach (var item in r)
        {
            Console.Write(" {0} ", item);
        }
        Console.WriteLine();
    }
}

class Program
{
    static void TestFoo()
    {
        Foo.PrintRange(Foo.Range(10, 20));
    }

    static void Main()
    {
        TestFoo();
    }
}

Expected Output:

10  11  12  13  14  15  16  17  18  19  20

Actual Output:

10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29

What is the problem with this code? Whats happening?

like image 738
Pratik Deoghare Avatar asked Dec 03 '22 13:12

Pratik Deoghare


1 Answers

The second parameter of Enumerable.Range specifies the number of integers to generate, not the last integer in the range.

If necessary, it's easy enough to build your own method, or update your existing Foo.Range method, to generate a range from start and end parameters.

like image 171
LukeH Avatar answered Dec 24 '22 13:12

LukeH