Translate

Saturday, April 30, 2011

Anonymous Types C# example


Instead of explicitly defining the types, you can let the compiler create that type for you in the background. These types where you do not explicitly declare the type, are called anonymous types.

In the example below, the compiler creates a class with three properties Name,Course and GPA in the background.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AnonymousExample
{
    class Program
    {
        static void Main(string[] args)
        {

            //The line below is a short cut technique to create an object with the name student
            //and set three public properties
            var student = new { Name = "Dilbert", Course = "C#", GPA = 3.0 };

            Console.WriteLine(student.GetType());
            //Displays <>f__AnonymousType0`3[System.String,System.String,System.Double]

            Console.WriteLine(student.Name);
            //Displays Dilbert


            //Properties set thru Anonymous types are read only
            student.Name = "Dilton"
//Throws compiler error:Error     1     Property or indexer 'AnonymousType#1.name' cannot be assigned to -- it is read only      
           

        }
    }
}

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator