Follow in Twitter & Facebook

Like in Facebook

Powered By Blogger Widgets

Free Download

FREE Tools

Thursday, August 16, 2012

What is Anonymous Types in C#.Net ?

In this article we will discuss about What is Anonymous types in C#.Net. Also you can check an article on Strings and StringBuilder in C# here.

- This comes with C#.Net 3.0

- Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.

- Mostly used in LINQ Query Expressions.

- Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object.

- Anonymous types are immutable.

- We can define the anonymous types with Var keyword like below:

var name = "SharePointDotNet Anonymous type";

Then internally it will convert to:

string name = "SharePointDotNet Anonymous type";

- There are certain rules to declare Anonymous types:

1. Anonymous types must always have an initial assignment and it can’t be null.

2. Anonymous types can be used with simple or complex types.

3. Anonymous types support IntelliSense.

4. Anonymous types cannot be used for a class field.

5. Anonymous types can be used as initializers in for loops.

6. Anonymous types can be used with arrays.

7. Anonymous types are all derived from the Object type.

8. Anonymous types can be returned from methods but must be cast to object.

Complex Anonymous Types examples:
var details = new {Name = "SharePointDotNet", Age = 5};

Internally it will convert to:

 private string name;
   private int age;

   public string Name
      get { return name; }
      set { name = value; }

   public int Age
      get { return age; }
      set { age = value; }

0 on: "What is Anonymous Types in C#.Net ?"