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:
- Creating Anonymous Type required
varkey word followed by the Type name. Later, we can use this name to access the members.
newkeyword here asks CLR to reserve space for the members. Size of memory space depends on the content of the data.
- 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.
- 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:
- 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 “
- 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:
5. Code Reference
static void Main(string args)
//Sample 01: Define Anonymous Type
var RahulS = new
Name = "Rahul Sinha",
Sex = "Male",
Age = 33,
Address = new
Street = "MG Road",
City = "Mumbai",
Country = "India"
Language = "Kannada"
//Sample 02: Use Anonymous Type
Console.WriteLine("Name of the Person : " + RahulS.Name);
Console.WriteLine("Sex : " + RahulS.Sex);
Console.WriteLine("Age : " + RahulS.Age);
Console.WriteLine("Address : " + RahulS.Address);
Console.WriteLine("Language : " + RahulS.Language);