Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

Anonymous Type in C#

1. Anonymous Type

In C#, Anonymous Type can encapsulate the properties for more code readability. These types can store only properties with a restriction that they can be read only. Note, it also lives for a short-term say within the function scope. Let us see a C# Example here to explore it.

2. Creating Anonymous Type

C# allows creating Anonymous Types using the var keyword followed by new key word. DotNet CLR allocates the required storage on the heap to hold the values assigned to the members of these Types. Now, look at the example below:

Fig 1. Defining Anonymous Type
Fig 1. Defining Anonymous Type


  1. Creating Anonymous Type required var key word followed by the Type name. Later, we can use this name to access the members.
  2. The new keyword here asks CLR to reserve space for the members. Size of memory space depends on the content of the data.
  3. Here, we assign the type names with the values. For example, Language is assigned with the string value “Kannada” and Age is assigned with a number value 33.
  4. An Anonymous Type can also have more types nested inside it. In our example, we have a type called Address which contains three members. Note the usage of the new keyword once again and it will create the nested type.

3. Accessing Anonymous Type’s Members

Just like a structure, we can access the members using the dot operator. To know in which City RahulS lives, we should use the dot operator twice. One is for Outer RahulS and other one is for inner Anonymous Type Address. Look at the code below:

Fig 2. Using Anonymous Types
Fig 2. Using Anonymous Types


  1. Here, we can see an example of how we access the Name of the person using dot operator. The same way, we can access other outer members of the RahulS. Suppose if we want to print the inner member say Street, we can fetch it as “RahulS.Address.Street”.
  2. In this marker, we fetched the entire Anonymous type and DotNet takes care of representing the members in string format. If you need your custom format, you can use the dot operator twice to get individual members and apply the needed formatting.

4. Output of the Example

When we run the above code, it will produce the following result:

Fig 3. Output of the Example
Fig 3. Output of the Example

5. Code Reference

Categories: C#

Tags: , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.