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!

1 comment:

  1. This type of tricks make .net easier and working.Your trick is very Nice and helpful for .Net programming developers.Math also comes with many tricks these tricks are helpful and funny.Math becomes enjoying and less boring due to these tricks during practice.
    Solve the given differential equation by separation of variables

    ReplyDelete