1. Anonymous types are new feature being added in C# 3.0.

2. These are data types being generated on the fly at the run time.

3. These data types are generated through complier rather than explicit class definition.

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication17
{
    class Program
    {
        static void Main(string[] args)
        {
 
            var MyAnonClass = new
            {
                Name = "Scott",
                Subject = "ASP.Net"
 
            };
 
 
            Console.WriteLine(MyAnonClass.Name);
            Console.Read();
 
 
        }
    }
}
 

Output

clip_image002

A class without name is being generated and assigned to implicitly type local variable

How it works internally?

1. For an anonymous type syntax compiler generates a class.

2. Properties of the complier generated class are value and data type given in declaration.

3. Intellisense supports anonymous type class properties.

clip_image003

4. Properties of one anonymous type can be used in declaration of another anonymous type.

clip_image004

Program.cs


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

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

            var MyAnonClass = new
            {
                Name = "Scott",
                Subject = "ASP.Net"

            };


            Console.WriteLine(MyAnonClass.Name);
            Console.Read();

            var SecondAnoynClass = new
            {
                info = MyAnonClass.Name + MyAnonClass.Subject
            };

            Console.WriteLine(SecondAnoynClass.info);
            Console.Read();
            Console.Read();
        }
    }
}


Output

clip_image006

Advertisements

One thought on “Anonymous types in C# 3.0

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s