Anonymous Types In C#

Introduction

Anonymous types allow us to create new types without defining them. The "type" of the type is decided by the compier. This is way to defining read only properties into a single object without having to define type explicitly. The type of properties is also inferred by the compiler.

Anonymous Types In C#

We can create anonymous types by using “new” keyword together with the object initializer. As you can see from the below code sample, the type is store in a var and has two data items.

Example

var anonymousData = new {  
    ForeName = "Jignesh",  
        SurName = "Trivedi"  
};  
Console.WriteLine("First Name : " + anonymousData.ForeName);  

Anonymous Types with LINQ Example

LINQ query expressions, and lambdas commonly use anonymous types. Anonymous types are used with the "Select" clause of LINQ query expression to return records.

Example

Let's say, an object collection have properties FirstName, LastName, MiddleName, and DOB, and you want only FirstName and LastName. The following code sample creates a List of MyData objects. The code then uses a LINQ query to return an anonymous type object.

class MyData {  
    public string FirstName {  
        get;  
        set;  
    }  
    public string LastName {  
        get;  
        set;  
    }  
    public DateTime DOB {  
        get;  
        set;  
    }  
    public string MiddleName {  
        get;  
        set;  
    }  
}  
static void Main(string[] args) {  
    // Create Dummy Data to fill Collection.  
    List < MyData > data = new List < MyData > ();  
    data.Add(new MyData {  
        FirstName = "Jignesh", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1990, 12, 30)  
    });  
    data.Add(new MyData {  
        FirstName = "Tejas", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1995, 11, 6)  
    });  
    data.Add(new MyData {  
        FirstName = "Rakesh", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1993, 10, 8)  
    });  
    data.Add(new MyData {  
        FirstName = "Amit", LastName = "Vyas", MiddleName = "P", DOB = new DateTime(1983, 6, 15)  
    });  
    data.Add(new MyData {  
        FirstName = "Yash", LastName = "Pandiya", MiddleName = "K", DOB = new DateTime(1988, 7, 20)  
    });  
}  
var anonymousData = from pl in data  
select new {  
    pl.FirstName, pl.LastName  
};  
foreach(var m in anonymousData) {  
    Console.WriteLine("Name : " + m.FirstName + " " + m.LastName);  
}  
}

Anonymous Types

Anonymous type is class type which is directly derived from “System.Object” and it cannot be cast by any type other than the object. The compiler generates a name for each anonymous type. If two or more anonymous type objects are defined in the same assembly and the sequence of properties are same in terms of names and types than the compiler treats both as same object instances of type. Fields, events, or the return type of a method cannot be anonymous types.

Anonymous Type vs Dynamic Type 

  • NET framework 4.0 introduced new keyword called "Dynamic". Object of dynamic type dynamic the static type checking at time of compilation whereas for anonymous type, creating static type and checking type at compile time.
  • Anonymous type is a class type that contain one or more read only properties whereas dynamic can be any type it may be any type integer, string, object or class.
  • Anonymous types are assigned types by the compiler.
  • Anonymous type is directly derived from System.Object whereas Dynamic differ from object type and DLR (Dynamic Language Runtime) define and assign type runtime.
  • Anonymous types throw compile time errors, Dynamic types does not throw any compile time error but throw run-time errors.
  • For Anonymous type, Visual studio able to show intellisense because type is known at the time compilation whereas intellisense is not available with dynamic because type is defined at runtime.

Dynamic Type example

dynamic dynamicData = 5;  
Console.WriteLine("Data of dynamic type : " + dynamicData);  
dynamicData = "Jignesh Trivedi";  
Console.WriteLine("Data of dynamic type : " + dynamicData);  

Dynamic type

Summary

  • Anonymous types are class type, directly derived from “System.Object” so they are reference types.
  • If two or more Anonymous types have same properties in same order in a same assembly then compiler treats them as same type.
  • All properties of anonymous types are read only.


Similar Articles