<

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

Be anonymous

Published on
9,040 Points
2,840 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

Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

Join & Write a Comment

Wrapper-1-Query. Use an Excel function to calculate a column for an Access query. Part 1. Shows a query in Access that has a calculated column with the results of an Excel worksheet function. See how to call a wrapper function from a query, and …
Overview of OneDrive and collaboration.

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month