I'm relatively new to C#, so if the answer to this question is obvious I apologise.
There's a portion of a program I am writing that stores an array of structs, and one of the elements of the struct is a curried function.
The following is the portion of code causing the problem (minimised as far as I am able)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CurryingProblem
{
class Program
{
public struct Value
{
public Func<decimal> Output;
}
public static decimal AddOne(decimal value)
{
return value + 1;
}
static void Main(string[] args)
{
Dictionary<string, Decimal> ThingsToAdd = new Dictionary<string, decimal>();
Dictionary<string, Value> ThingsToPrint = new Dictionary<string, Value>();
ThingsToAdd.Add("One", 1.0m);
ThingsToAdd.Add("Two", 2.0m);
foreach (KeyValuePair<string, Decimal> thing in ThingsToAdd)
{
Value value = new Value();
value.Output = () => AddOne(thing.Value);
ThingsToPrint.Add(thing.Key, value);
}
Console.WriteLine(ThingsToPrint["One"].Output());
Console.WriteLine(ThingsToPrint["Two"].Output());
Console.ReadKey();
}
}
}
The expected output of this program is
2.0
3.0
But the actual output is
3.0
3.0
Any direction as to where I've gone wrong would be wonderful.