tags:

views:

146

answers:

3
+1  Q: 

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());
            }
        }

    }
+1  A: 

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".

Greg B
+3  A: 
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).

shahkalpesh