In C# programming, anonymous types enable the creation of objects with properties that are read-only. These objects are typeless, with the compiler assigning a unique type name that is limited to the code block in which it is defined.
In C#, the concept of anonymous types was first introduced in C# 3.0. They simplify the process of grouping a collection of read-only properties without the need to declare a distinct class. Anonymous types are commonly employed in LINQ queries to store a transient dataset in a succinct and type-secure fashion, eliminating the necessity of defining a formal class.
The <style> class styles a diagram placeholder with a linear gradient background, rounded corners, padding, and center alignment. Inside, there is an icon with a size of 3rem and text with a color of #9ca3af and font size of 1rem. </style>
Syntax:
It has the following syntax.
var variableName = new { PropertyName1 = value1, PropertyName2 = value2, PropertyName2 = value2, ... };
In this structure,
- var: The var keyword is utilized for defining the unnamed type.
- new{ .. }: The new keyword is employed for generating an object without a designated class.
C# Simple Anonymous Type Example
Let's consider a scenario to showcase the application 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 instance, an anonymous type s has been defined with its attributes Name, Age, and Course utilizing the fresh {..} syntax. Subsequently, a class is automatically produced by the compiler for this type, followed by showcasing the property values through the Console.WriteLine function.
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 C#, utilizing a nested anonymous type enables the creation of an anonymous type within a property of another anonymous type. This extends the concept by allowing any of those properties to be anonymous objects as well.
C# Nested Anonymous Types Example
Let's consider an example to demonstrate the concept of a 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 instance, a variable named stu is defined to hold an unidentified object with various attributes like Name, Age, and Course. Following this, a nested anonymous type is constructed within it, comprising the attributes City, State, and Country. Subsequently, the values of these embedded attributes are retrieved using the dot(.) notation. Ultimately, the output is presented using the Console.WriteLine method.
Anonymous type in LINQ
In C# programming, an anonymous type offers a way to bundle a group of properties that are read-only into a singular property without the need to create a formal class structure. This feature is frequently employed in LINQ queries to extract particular properties.
C# Anonymous type in LINQ Example
Let's consider a scenario to demonstrate the concept of anonymous types in C# using LINQ.
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 instance, we've established an array comprising anonymous entities, with each entity including solely the Name, Age, and Course attributes. Subsequently, we employ a LINQ query to filter out students whose course is C#. Within the filtered selection, we define a new anonymous type that includes solely the Name and Age of the selected students. Lastly, the output is exhibited using the Console.WriteLine method.
Difference between Anonymous Type and Dynamic Type in C#
There exist various distinctions between the anonymous type and the dynamic type in C#. A few of these variances are outlined below:
| 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 summary, the C# anonymous type enables the creation of transient and lightweight objects without the need to declare a class. These objects are immutable and are considered as reference types. They prove beneficial in LINQ queries by facilitating the selection of particular properties, streamlining data management in a succinct and effective manner.
C# Anonymous type FAQs
1) What is an anonymous type in C#?
In C# programming, anonymous types enable the creation of objects with properties that are read-only. They are objects without a specified type, as the C# compiler generates a unique type name for them, accessible solely within the current code block.
2) What is a nested anonymous type in C#?
In C#, a nested anonymous type enables the creation of an anonymous type within a property of another anonymous type.
3) Can anonymous types be used in LINQ queries?
In C#, an anonymous type offers a way to group a collection of read-only properties under a single property without the need to declare a class explicitly.
var result = from s in students
select new {s.Name, s.Age};
4) How do we create an Anonymous type in C#?
We have the ability to generate an unidentified type by employing the new keyword in conjunction with an object initializer. The syntax for this operation is as follows:
var variableName = new {PropertyName1 = value1, PropertyName2 = value2, PropertyName2 = value2, ...};
5) Can Anonymous Types have null values in C#?
Yes, Anonymous types can contain null values within their properties, similar to standard reference types.
var emp = new {Name = (string?)null, Age = 25};