Be anonymous

AID: 2113
  • Status: Published

1420 points

  • Byivostoykov
  • TypeTutorial
  • Posted on2009-12-16 at 06:37:19
Anonymous Types in C#
by Ivo Stoykov

Anonymous Types are useful when  we do not need to follow usual work-flow -- creating object of some type, assign some read-only values and then doing something with them. Instead we can encapsulate this read only data into an anonymous type without first defining object explicitly. (Anonymous simply means "without a name".)

Anonymous types are class types that consist of one or more public read-only properties.

In C# 3.0 compiler generates anonymous types through object initializer, who cares to use appropriate types assigning given values to one or more fields or properties of an object. This is why anonymous types are not available in source code level.
Objects declared as anonymous types use the var keyword in place of the type name. Dislike JavaScript the var keyword here always generates a strongly typed variable reference.

Sample:
var v = new { Amount = 108, Message = "Hello" };
                                    
1:

Select allOpen in new window



Note that there is no name for the class. Therefore, in declaration, we cannot specify type in front of the variable. Instead the var keyword is used.

var tells the compiler that we leave to it to infer the type of the variable for us. The var keyword can be used to reference any type in C#. So following declaration
var name = "Scott";
                                    
1:

Select allOpen in new window


is identical with
String name = "Scott";
                                    
1:

Select allOpen in new window



Because the var keyword produces a strongly-typed variable declaration, the compiler needs to be able to infer the type to declare based on its usage.  This means that you need to always do an initial value assignment when declaring one. The compiler will produce a compiler error if you don't:

var name; // will generate error
var name = "Scott"; // will compile clean
                                    
1:
2:

Select allOpen in new window



Note that in the sample above
var v = new { Amount = 108, Message = "Hello" };
                                    
1:

Select allOpen in new window


the usage of the new keyword. It is used without a type name. What follows the new keyword is the object initializer mentioned previously. It is its duty to create a class for us with declared properties.

So for our v variable it will create
class __NONAME__
{
  public int Amount { get; set; }
  public string Message  { get; set; }
}
                                    
1:
2:
3:
4:
5:

Select allOpen in new window



Note  that object initializer works out the type from the expression used to initialize the variable when it is first declared.

Sample:

 
// Program.cs
using System;
using System.Query;
using System.Data.DLinq;
namespace AnonTypes
{
   class Program
   {
      static void Main(string[] args)
      {
         var p1 = new {Name = "A", Price = 3}; /* creates new anonymous type with String value A for property Name and int value 3 for property Price */
         Console.WriteLine("Name = {0}\nPrice = {1}",
                           p1.Name, p1.Price);
         Console.ReadLine();
      }
   }
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:

Select allOpen in new window




Limitation

Anonymous Type (type = class in this case) are greatly limited compared to standard classes. They can only inherit from object and their only memebers are private fields.
Asked On
2009-12-16 at 06:37:19ID2113
Tags

C# NET framework anonymous type develop

Topic

C# Programming Language

Views
770

Comments

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top C# Experts

  1. kaufmed

    566,376

    Sage

    500 points yesterday

    Profile
    Rank: Genius
  2. BuggyCoder

    240,764

    Guru

    10 points yesterday

    Profile
    Rank: Sage
  3. navneethegde

    158,560

    Guru

    0 points yesterday

    Profile
    Rank: Wizard
  4. CodeCruiser

    140,708

    Master

    2,000 points yesterday

    Profile
    Rank: Genius
  5. TheLearnedOne

    137,350

    Master

    2,800 points yesterday

    Profile
    Rank: Savant
  6. wdosanjos

    124,511

    Master

    3,500 points yesterday

    Profile
    Rank: Genius
  7. AndyAinscow

    107,357

    Master

    0 points yesterday

    Profile
    Rank: Genius
  8. Dhaest

    98,335

    Master

    0 points yesterday

    Profile
    Rank: Genius
  9. Idle_Mind

    91,914

    Master

    0 points yesterday

    Profile
    Rank: Savant
  10. tommyBoy

    90,068

    Master

    0 points yesterday

    Profile
    Rank: Genius
  11. nishantcomp2512

    89,000

    Master

    0 points yesterday

    Profile
    Rank: Wizard
  12. MlandaT

    86,553

    Master

    0 points yesterday

    Profile
    Rank: Genius
  13. Chinmay_Patel

    80,818

    Master

    0 points yesterday

    Profile
    Rank: Genius
  14. ddayx10

    66,538

    Master

    0 points yesterday

    Profile
    Rank: Sage
  15. anarki_jimbel

    66,132

    Master

    2,000 points yesterday

    Profile
    Rank: Genius
  16. ambience

    63,764

    Master

    0 points yesterday

    Profile
    Rank: Sage
  17. ukerandi

    62,593

    Master

    1,000 points yesterday

    Profile
    Rank: Guru
  18. apeter

    60,772

    Master

    0 points yesterday

    Profile
    Rank: Sage
  19. JamesBurger

    60,305

    Master

    0 points yesterday

    Profile
    Rank: Sage
  20. sedgwick

    52,750

    Master

    1,600 points yesterday

    Profile
    Rank: Genius
  21. emoreau

    50,917

    Master

    0 points yesterday

    Profile
    Rank: Genius
  22. ged325

    50,311

    Master

    2,000 points yesterday

    Profile
    Rank: Genius
  23. anuradhay

    49,977

    2,500 points yesterday

    Profile
    Rank: Guru
  24. techChallenger1

    47,638

    0 points yesterday

    Profile
    Rank: Guru
  25. mas_oz2003

    43,540

    0 points yesterday

    Profile
    Rank: Genius

Hall Of Fame