.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Anonymous types in C#

Posted By:Dhananjay Kumar       Posted Date: September 08, 2010    Points: 25    Category: C#    URL: http://www.dotnetspark.com  

In this article you will leann how to use Anonymous types in C# 3.0. Anonymous types are new feature being added in C# 3.0. These are data types being generated on the fly at the run time.
 

  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

anan1.gif

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.

    anan2.gif

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

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();

       }

   }

} 
Output

anan5.gif

 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend