CSharp - Create Anonymous Types

Introduction

An anonymous type has no name and is generated by the compiler based on the initialization of the object.

The anonymous type is used when projecting new data types using the Select or SelectMany operators.

The following code does the Instantiating and Initializing an Anonymous Type Using Object Initialization

We added that last call to the Console.WriteLine method just so you can see the internal compiler-generated name for the anonymous class.

Here are the results:

Demo

using System;  
using System.Linq;  
class Program/*from   w w w.ja  v a 2s . c o m*/
{
    static void Main(string[] args)
    {
        var address = new {  
                        address = "105 Elm Street",  
                        city = "Atlanta",  
                        state = "GA",  
                        postalCode = "30339"  
                      };  
          
        Console.WriteLine("address = {0} : city = {1} : state = {2} : zip = {3}",  
          address.address, address.city, address.state, address.postalCode);  
          
        Console.WriteLine("{0}", address.GetType().ToString());  
    }
}

Result

Related Topic