Search code examples
c#anonymous-methods

Error in Anonymous Method contained variable


I have the following method. When the Writeline Methods are calling, missing results arise. The result of the second Writeline must true otherwise, it is false, could you please advise me?

    public static void IsGreater()
    {
       var biggerThanNumber = new Predicate<int>[10];
       for (int index = 0; index < biggerThanNumber.Length; ++index)
       {
         biggerThanNumber[index] = value => value > index; 
       }
       Console.WriteLine(biggerThanNumber[5](20)); //True
       Console.WriteLine(biggerThanNumber[5](6));  //False
    }

Solution

  • Change the method to copy loop variable into a local reference to avoid lambda closure issue in a loop. In your method value of index is always 10 hence second the console is returning false. For more info check this post

        public static void IsGreater()
        {
            var biggerThanNumber = new Predicate<int>[10];
            for (int index = 0; index < biggerThanNumber.Length; ++index)
            {
                int localCopy = index;
                biggerThanNumber[index] = value => value > localCopy;
            }
            Console.WriteLine(biggerThanNumber[5](20)); //True
            Console.WriteLine(biggerThanNumber[5](6));  //True
        }