var in C# . . . why?

Here is the link to Microsoft’s discussion of the var keyword in C#.

At first reading of this, it appears to be a simple way of not having to explicitly think about the types of your objects. However, it’s a little more involved than that. It’s useful for when you deal with anonymous types. What’s an anonymous type?

Here’s the link to Microsoft’s discussion of anonymous types.

Anonymous types are class types that derive directly from object, and that cannot be cast to any type exceptobject. The compiler provides a name for each anonymous type, although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type.

Here’s some code I created to play around with LINQ in the context of anonymous types . . .

 

        static void Main(string[] args)
        {
            // The Three Parts of a LINQ Query: 
            //  1. Data source. 
            //int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
            var stuff = new[] {new { Number = 0, Fruit = "Apple", Birthday = new DateTime(1968, 5, 31) }, 
                             new { Number = 2, Fruit = "Orange", Birthday = new DateTime(1971, 6, 3) }};

            // 2. Query creation. 
            // stuffQuery is an IEnumerable<?> 
            var stuffQuery =
                from item in stuff
                select new { item.Number };

            // 3. Query execution. 
            foreach (var thing in stuffQuery)
            {
                Console.WriteLine("thing: {0} ", thing.Number);
            }
        }
Posted in C#