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 };

            //Displays <>f__AnonymousType0`3[System.String,System.String,System.Double]

            //Displays Dilbert

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


No comments:

Post a Comment

Comments will appear once they have been approved by the moderator