user215675
user215675

Reputation: 5181

C# Func delegate

I am adding range of integers (101,105) using Func<> delegate.I suppose to get 101,102,..105 as output while executing the following.But I am getting 204,204,..... What went wrong?

class MainClass
    {
       static List<Func<int>> somevalues = new List<Func<int>>();
        static void Main()
        {
            foreach (int r in  Enumerable.Range(100, 105))
            {
                somevalues.Add(() => r);
            }

            ProcessList(somevalues);
            Console.ReadKey(true);
        }

        static void ProcessList(List<Func<int>> someValues)
        {
            foreach (Func<int> function in someValues)
            {
                Console.WriteLine(function());
            }
        }

    }

Upvotes: 2

Views: 2130

Answers (3)

shahkalpesh
shahkalpesh

Reputation: 33476

foreach (int r in  Enumerable.Range(100, 105))
{
   int s = r;
   somevalues.Add(() => s);
}

I think, you will need to capture the outer variable into a temp value to achieve the output, you need. I am not sure of what is the concept called (captured variables maybe).

Upvotes: 3

Greg B
Greg B

Reputation: 14888

THe Range method signiture is like follows:

Range(int start, int count);

you are saying "start at 100 and give me the next 105 numbers".

not, "start at 100 and finish at 105".

Upvotes: 1

Related Questions