<

Be anonymous

Published on
8,983 Points
2,783 Views
2 Endorsements
Last Modified:
Approved
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" };

Open 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";

Open in new window

is identical with
String name = "Scott";

Open 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

Open in new window


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

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

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

Open 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.
2
Comment
Author:Ivo Stoykov
0 Comments

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Join & Write a Comment

How to fix display issue, screen flickering issue when I plug in power cord to the machine. Before I start explaining the solution lets check out once the issue how it looks like after I connect the power cord. most of you also have faced this…
Did you know PowerShell can save you time with SaaS platforms? Simply leverage RESTfulAPIs to build your own PowerShell modules. These will kill repetitive tickets and tabs, using the command Invoke-RestMethod. Tune into this webinar to learn how…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month