Friday, June 11, 2010

.NET Trick Question

What do you think will be the output of the following code:

    class Program
    {
        public class StringClass
        {
            public string TheString { get; set; }
        }
 
        static void Main(string[] args)
        {
            List<StringClass> stringClassList = new List<StringClass>(){
                new StringClass{TheString="asdf"}
            };
 
            IEnumerable<StringClass> stringClassEnumerable = stringClassList;
 
            IEnumerable<StringClass> AllItems = stringClassEnumerable.Where(item => (true));
 
            stringClassList.Add(new StringClass { TheString = "fdsa" });
 
 
            foreach (StringClass item in AllItems)
            {
                Console.WriteLine(item.TheString);
            }
 
            Console.ReadKey();
 
        }
    }


If you think the output is :
asdf

You are wrong.
It is :
asdf
fdsa

This is because the result from the where extension methods is deferred till you try to access the result (in this case the foreach loop).

Enjoy!