Source

ITSWITCH: #1

Is There Something Wrong In This Code Here

UPDATE: as several readers pointed out there was compile error in the code what was being displayed.  The line “String value = string[i]” was showing up as “String value = string”.  I’m not sure why; but throwing some spaces between the i and the square brackets seems to have solved it.

In the following class, is there something wrong with either InitializeOne or InitializeTwo (hint, it has nothing to do with compile errors and I’m ignoring performance differences)?

    public class TestClass


    {


        private List<MethodInvoker> delegates;


 


        private static void ProcessText(String text)


        {


            Trace.WriteLine(text);


        }


 


        public void Run()


        {


            foreach(MethodInvoker invoker in delegates)


            {


                invoker();


            }


        }


 


        public void InitializeOne(String[] strings)


        {


            delegates = new List<MethodInvoker>(strings.Length);


            for (int i = 0; i < strings.Length; ++i)


            {


                String value = strings[ i ];


                delegates.Add(delegate { ProcessText(value); });


            }


        }


 


        public void InitializeTwo(String[] strings)


        {


            delegates = new List<MethodInvoker>(strings.Length);


            foreach(String value in strings)


            {


                delegates.Add(delegate { ProcessText(value); });


            }


        }


    }

Answer on Monday.

with : , , , , , ,