In the C# programming language, anonymous types allow us to create an object that has read-only properties. An anonymous object is an object that has no explicit type. The C# compiler generates a type name and is accessible only for the current block of code.
In C#, anonymous types were introduced in C# 3.0. They make it easier to encapsulate a set of read-only properties without defining a separate class. It is mainly used in LINQ queries to hold a temporary set of data in a concise and type-safe manner without creating a class.
Syntax:
It has the following syntax.
var variableName = new { PropertyName1 = value1, PropertyName2 = value2, PropertyName2 = value2, ... };
In this syntax,
- var: The var keyword is used to declare the anonymous type.
- new{ .. }: The new keyword is used to create an object without a named class.
C# Simple Anonymous Type Example
Let us take an example to demonstrate the use of an anonymous type in C#.
Example
using System;
class C# Tutorial
{
static void Main()
{
// creating an anonymous type
var s = new {Name = "John", Age = 22, Course = "C#"};
// displaying property values
Console.WriteLine("The Student Details are ");
Console.WriteLine("The name is " + s.Name);
Console.WriteLine("The age is " + s.Age);
Console.WriteLine("The course is " + s.Course);
}
}
Output:
The Student Details are
The name is John
The age is 22
The course is C#
Explanation:
In this example, we have created an anonymous type s with its properties Name, Age, and Course using the new {..} keyword. After that, the compiler automatically generates a class for it, and then we display the property values using the Console.WriteLine method.
Key Points of Anonymous Type
There are several key points of the Anonymous types in C#. Some of them are as follows:
- In the C# programming language, anonymous types are read-only types, which means that properties cannot be changed once they are initialized.
- The compiler automatically generates a class with auto-implemented read-only properties.
- Anonymous types are local and accessible only within the block of code where they are declared.
- Anonymous type is derived from the System.Object class. It is also a sealed class.
- An anonymous type is also called the reference type.
- We can also create an array of anonymous types to store multiple anonymous objects.
C# Nested Anonymous Type
In the C# programming language, a nested anonymous type allows us to create an anonymous type inside the property of another anonymous type. A nested anonymous type spreads this concept by enabling one or more of those properties to be anonymous objects themselves.
C# Nested Anonymous Types Example
Let us take an example to illustrate the nested anonymous type in C#.
Example
using System;
class C# Tutorial
{
static void Main()
{
// creating a nested anonymous type
var stu = new
{
Name = "Michael",
Age = 22,
Course = "C#",
Address = new
{
City = "New York",
State = "New York",
Country = "US"
}
};
// Displaying values of outer anonymous type
Console.WriteLine("Student Details are ");
Console.WriteLine("The name is " + stu.Name);
Console.WriteLine("The age is " + stu.Age);
Console.WriteLine("The course is " + stu.Course);
// Displaying values of nested anonymous type
Console.WriteLine("\nAddress Details:");
Console.WriteLine("The city is " + stu.Address.City);
Console.WriteLine("The state is " + stu.Address.State);
Console.WriteLine("The country is " + stu.Address.Country);
}
}
Output:
Student Details are
The name is Michael
The age is 22
The course is C#
Address Details:
The city is New York
The state is New York
The country is US
Explanation:
In this example, we have taken a variable stu that represents an anonymous object that contains several properties, such as Name, Age, and Course. After that, we create another anonymous type inside it that includes the Properties City, State, and Country. After that, we use the dot(.) property to access the values of these nested properties. Finally, we use the Console.WriteLine method to display the output.
Anonymous type in LINQ
In the C# programming language, an anonymous type provides a mechanism to encapsulate a set of read-only properties into a single property without defining a class. It is commonly used for LINQ queries to select specific properties.
C# Anonymous type in LINQ Example
Let us take an example to illustrate the anonymous type with LINQ in C#.
Example
using System;
using System.Linq;
class C# Tutorial
{
static void Main()
{
// Array of students
var stu = new[]
{
new{Name = "Johnson", Age = 22, Course = "C#"},
new{Name = "Anderson", Age = 20, Course = "Java"},
new{Name = "Michael", Age = 23, Course = "C#"}
};
// Using LINQ
var csStu = from s in stu
where s.Course == "C#"
select new
{
s.Name,
s.Age
};
Console.WriteLine("The C# Students are");
foreach (var s in csStu)
{
Console.WriteLine($" Name: {s.Name}, Age: {s.Age} ");
}
}
}
Output:
The C# Students are
Name: Johnson, Age: 22
Name: Michael, Age: 23
Explanation:
In this example, we have created an array of anonymous objects, where each object contains only the Name, Age, and Course properties. After that, we use the LINQ query to select only those students whose course is C#. In the selected part, we create an anonymous type again, which contains only the Name and Age of the filtered students. Finally, we use the Console.WriteLine method to display the output.
Difference between Anonymous Type and Dynamic Type in C#
There are several differences between the anonymous type and the dynamic type in C#. Some of them are as follows:
| Feature | Anonymous Type | Dynamic Type |
|---|---|---|
| Definition | Anonymous types are the types created by the compiler at runtime to hold a set of read-only properties without explicitly defining a class. | Dynamic types are types that can be resolved at runtime rather than compile time. |
| Declaration | Anonymous type can be declared by using the var keyword. | Dynamic Type can be declared by using the dynamic keyword. |
| Namespace | Anonymous type has no special namespace required. | Dynamic type requires using System.Dynamic namespace. |
| Performance | Anonymous type is faster during execution. | Dynamic type is slower during execution. |
| Example | Example of an Anonymous type is:var person = new { Name = "John", Age = 25 }; | Example of Dynamic Type isDynamic person = new ExpandoObject();Person.Name = "John"; person.Age = 25; |
Advantages of Anonymous Type
There are several advantages of anonymous types in C#. Some of them are as follows.
- It is useful when we want to hold the temporary data.
- It reduces the need to create a separate model class for a small task.
- It improves development speed for data transformation.
- It makes the code shorter and more readable.
- It can be used with LINQ queries to select specific properties.
Limitations of Anonymous Type
There are several limitations of the anonymous type in C#. Some of them are as follows:
- The properties of an anonymous type are read-only. We cannot modify their values after initialization.
- We cannot declare a method to return an anonymous type.
- An anonymous type has no type name. We can return an anonymous type only as an object or use the var keyword within the same method.
- We cannot define a custom method inside an anonymous type.
- Anonymous types are sealed and cannot participate in inheritance.
Conclusion:
In conclusion, the C# anonymous type allows us to create temporary and lightweight objects without defining a class. They are read-only and reference types. It is useful for LINQ queries to select specific properties and simplify data handling in a concise and efficient way.
C# Anonymous type FAQs
1) What is an anonymous type in C#?
In the C# programming language, anonymous types allow us to create an object that has read-only properties. An anonymous object is an object that has no explicit type. The C# compiler generates a type name and is accessible only for the current block of code.
2) What is a nested anonymous type in C#?
In C#, a nested anonymous type allows us to create an anonymous type inside the property of another anonymous type.
3) Can anonymous types be used in LINQ queries?
In C#, an anonymous type provides a mechanism to encapsulate a set of read-only properties into a single property without defining a class.
var result = from s in students
select new {s.Name, s.Age};
4) How do we create an Anonymous type in C#?
We can create an anonymous type using the new keyword along with an object initializer. It has the following syntax:
var variableName = new {PropertyName1 = value1, PropertyName2 = value2, PropertyName2 = value2, ...};
5) Can Anonymous Types have null values in C#?
Yes, Anonymous types can have null values in their properties, just like regular reference types.
var emp = new {Name = (string?)null, Age = 25};