Understanding C# Anonymous Types | Syncfusion Blogs
Detailed Blog page Skeleton loader
Understanding C# Anonymous Types

The anonymous types in the C# programming language provide an easy way to encapsulate different properties in a single object. Unlike properties in a class, the properties of the anonymous type objects are read-only. We can create read-only properties in a class, but not all properties are mandatorily read-only.

For better understanding, you can call an anonymous type a class with only public read-only objects. It is not allowed to hold methods, events, and other elements of a class.

In this blog, we will cover the following topics:

Declaring and using an anonymous type object

The keyword var is used to declare anonymous type objects. The new operator, along with an object initializer, is used to define the value.

The following code example illustrates the declaration and initialization of the anonymous type with two properties, Username and Password.

var loginCredentials = new { Username = "suresh", Password = "********" };

Console.WriteLine("Username " + loginCredentials.Username.ToString());
Console.WriteLine("Password " + loginCredentials.Password.ToString());

After assigning values to the UserName and Password properties, they cannot be altered, as they are read-only. Trying to modify the values will result in an error.
Code showing an error message while altering the username and password

Anonymous objects in a LINQ query

Usually, an anonymous data type is used in the select clause of a LINQ expression to return a subset of properties from each object in the collection.

In the following code example, we will see using an anonymous object in a LINQ query.

class Program
{
    static void Main(string[] args)
    {
        IList<Employee> employees = new List<Employee>() {
        new Employee() { ID = 101, Name = "Peter", Age = 27 },
        new Employee() { ID = 102, Name = "Parker",  Age = 35 },
        new Employee() { ID = 103, Name = "Robert",  Age = 32 },
    };

        var employeeDetails = from emp in employees
                              select new { Id = emp.ID, Name = emp.Name, Age = emp.Age };

        foreach (var employeeDetail in employeeDetails)
            Console.WriteLine(employeeDetail.Id + "-" + employeeDetail.Name + "-" + employeeDetail.Age);
    }
}

public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

The output of the execution of this code example will be the following.
Result

Passing an anonymous object as method parameter

Usually, it is not recommended to pass or return an anonymous object as a method parameter or return object. Handling it as an object is quite tedious, and in these cases, it’s preferred to use class or struct types.

Using an anonymous type as the method parameter is explained here just for your knowledge.

When an anonymous type object is passed as a parameter, it is received as the object type. The received object cannot be used as such. We have to access the type of the object and acquire the PropertyInfo from the type to access the property’s values.

The following code example illustrates accessing the property values of the anonymous object.

static void Main(string[] args)
{
    var loginCredentials = new { UserName = "suresh", Password = "********" };
    PrintValues(loginCredentials);
}

static void PrintValues(object credentials)
{
    Type type = credentials.GetType();
    PropertyInfo[] info = type.GetProperties();

    foreach (var item in info)
    {
        var value = item.GetValue(credentials);
        Console.WriteLine(value.ToString());
    }
}

The execution of this code will result in the following.

Result Conclusion

I hope you now have a clear idea of anonymous types in C# programs. Use this type wisely in your program wherever applicable.

Syncfusion provides more than 1,600 custom controls to ease the work of developers on various platforms. Please have a look and use them in your application development:

Be the first to get updates

Suresh M

Meet the Author

Suresh M

Suresh is a Product Manager at Syncfusion and a technology enthusiast. He helps people follow best practices in coding and in using Syncfusion controls in their applications. Follow Syncfusion Blogs to learn and enhance your programming skills.