Wednesday, November 23, 2011

Anonymous Types in C#


Load Java Version
Anonymous Types are a quick way to work with datasets and objects "on the fly". Though I still don't know the issues in terms on software maintenance and all - they can be pretty usable (not to mention the entire Linq is based on this )


I am posting snippets of code that I've worked with - might be helpful for beginners.

Collections and Anonymous Types


ArrayList

            var firstPerson = new { Age = 20, Firstname = "John", Lastname = "Smith", City = "Chicago" };
            var secondPerson = new { Age = 21, Firstname = "Mary", Lastname = "Green", City = "SFO" };
           
            ArrayList students = new ArrayList();
            students.Add(firstPerson);
            students.Add(secondPerson);

            Type declaredType = firstPerson.GetType(); // get the Type of the anonymous type.
            foreach (object s in students)
            {
                Type resolvedType = s.GetType(); // now get the Type of the retrieved object 
                                                from ArrayList - all are object by default -
                if (resolvedType.Equals(declaredType)) // Compare the types for equality 
                {
                    dynamic d = s; // MUST use dynamic as narrowing down/casting 
                                                to Anonymous type is not possible (?)
                    Console.WriteLine(d.age);
                }
            }