Monday, May 27, 2013

Anonymous Types

Anonymous types allow us to define variables and classes dynamically at runtime without having to declare them beforehand. The following example creates a string variable MyName dynamically at runtime without any specific declaration.

    var MyName = "Test Name";

When this code executes the output will be as follows


This shows that the compiler automatically assigns the type String to the variable MyName, though it was not explicitly declared at design time. Once a type is assigned to an Anonymous type it cannot be altered by assigning a different value, trying to do so will throw an error. The below line of code tries to assign an integer value to the string anonymous type declared above and hence will throw a type casting error.

MyName = 123;

If you try to compile the above line the following error is thrown.

Cannot implicitly convert type 'int' to 'string'

We have seen on how to create anonymous types which represent simple types like sting and integer, we can also define dynamic anonymous classes whose member variables and properties are specified dynamically at run time. In the below example we will create an anonymous type which is defined dynamically at runtime and holds the details of an employee.

    var empDetails = new { Name = "Test Name", Age = 32, Address = "Test Address" };

When this code executes the output will be as follows


The compiler has automatically created a dynamic type based on the set of values assigned to the Anonymous type.

Also the Properties Name, Age and Address are automatically created for the type empDetails. You can notice this by accessing the Intellisense of the Type as follows.

Search Flipkart Products:

No comments: