Dot Net Stuff

Understanding and Programming with Anonymous Types in C#


Anonymous types use the keyword var. Var is also used in Pascal and Delphi today, but var in Delphi is like ByRef in Visual Basic (VB) or ref in C#. The var introduced with .NET 3.5 indicates an anonymous type. Now, our VB friends are going to think, “Well, we have had variants for years in VB.” But var is not a dumbing down and clogging up of C#. Anonymous types are something new and necessary.

The simple meaning of Anonymous is that you don’t specify the type. You write var and C# figures out what type is defined by the right side, and C# emits (writes the code), indicating the type. From that point on, the type is strongly defined, checked by the compiler (not at runtime), and exists as a complete type in your code. There is one point to remember, you didn’t write the type definition; C# did.

Understanding Anonymous Types

Anonymous types defined with var are not VB variants. The var keyword signals the compiler to emit a strong type based on the value of the operator on the right side. Anonymous types can be used to initialize simple types like integers and strings. When such an anonymous type is defined, the compiler emits an immutable read-only properties and the class referred to as a projection. Anonymous types support IntelliSense, but the class should not be referred to in code, just the members.

There are some basic rules for using anonymous types:

  1. Anonymous types must always have an initial assignment and it can’t be null because the type is inferred and fixed to the initializer.
  2. Anonymous types can be used with simple or complex types but add little value to simple type definitions.
  3. Composite anonymous types require member declarators; for example,
     
     var fruits = new {Name="Apple"  [, declaratory=value, ...]}.
    
    (In the example, Name is the member declaratory.)
  4. Anonymous types support IntelliSense.
  5. Anonymous types cannot be used for a class field.
  6. Anonymous types can be used as initializers in for loops.
  7. The new keyword can be used and has to be used for array initializers.
  8. Anonymous types can be used with arrays.
  9. Anonymous types are all derived from the Object type.
  10. Anonymous types can be returned from methods but must be cast to object, which defeats the purpose of strong typing.
  11. Anonymous types can be initialized to include methods, but these might only be of interest to linguists.

Finally, because anonymous types are immutable—you can think about no property setters—two separately defined anonymous types with the same field values are considered equal.

How to use Anonymous Types in C#

Anonymous type begins with the var keyword, the assignment operator (=), and a non-null initial value. The anonymous type is assigned to the name on the left side of the assignment operator. Following is an example.

 
var title = "DotNet-Tutorial for C#";

The above code is equal to following code in C#.

 
String title = "DotNet-Tutorial for C#";

Let's see how we can define array using Anonymous Types in c #. Following is an example shows how we can define array using Anonymous Types.

 
// array initializer with Anonymous Types 
var numbers = new int[]{ 1, 1, 2, 3, 5, 8, 13, 21 };
Console.WriteLine(numbers[0]);
Console.ReadLine();

The above array is same as following code in C#

 
// array initializer with Anonymous Types 
int []numbers = new int[]{ 1, 1, 2, 3, 5, 8, 13, 21 };
Console.WriteLine(numbers[0]);
Console.ReadLine();

Composite Anonymous Types

Anonymous types can be really useful when they are used to define composite types, that is, classes without the “typed” class definition. In another word use of anonymous types as defining an inline class without all of the typing. Following example shows an anonymous type representing a Student class.

 
var student = new {FirstName="Demo", LastName="Student"};
//student.FirstName = "Good Stuff"; // throws an error - immutable
Console.WriteLine(student);
Console.ReadLine();

Above code shows how can you define inline class using Anonymous Types, which is called Composite Anonymous Types. Also, you can add methods to very same inline class. Let's continue with above example and try to add a method.

 
//Generic delegate 
Func<string, string> GetFullName =
delegate(string firstName, string lastName)
{
return firstName + " " + lastName;
};
var student = new {FirstName="Demo", LastName="Student", FullName=GetFullName};
//access the full Name
Console.WriteLine(student.GetFullName(student.FirstName, student.LastName));
Console.ReadLine();

Summary: The var keyword can be used to initialize variable, array, index of a for loop or the recipient object of a foreach loop. Anonymous Type can also be used in DataBinding and Using Statement. It is really a powerful feature of c#. In this article we had learnt about Anonymous Type and it’s uses with implementation. We will try to understand the Anonymous Methods and some other powerful concepts of c# in separate articles.


Keen to hear from you...!

If you have any questions related to what's mentioned in the article or need help with any issue, ask it, I would love to here from you. Please MakeUseOf Contact and i will be more than happy to help.

About the author

Anil Sharma is Chief Editor of dotnet-stuff.com. He's a software professional and loves to work with Microsoft .Net. He's usually writes articles about .Net related technologies and here to shares his experiences, personal notes, Tutorials, Examples, Problems & Solutions, Code Snippets, Reference Manual and Resources with C#, Asp.Net, Linq , Ajax, MVC, Entity Framework, WCF, SQL Server, jQuery, Visual Studio and much more...!!!

Loading