C# Anonymous Types

Anonymous type in C# allows us to create a type without specifying the name. For example,

var subject = new {Name = "Math", Code = 123};

Here, subject is an anonymous type variable containing two properties: Name and Code.

You can see we have used a new operator to create an anonymous type.


Example: C# Anonymous Type

using System;
class Program
{
    static void Main()
    {
// create an anonymous type containing 3 properties var person = new { Age = 34, Name = "John", Address = "Miami" };
// display the anonymous type Console.WriteLine(person); } }

Output

{ Age = 34, Name = John, Address = Miami }

In the above example, person is an anonymous type variable with properties: Age, Name, and Address with values 32, "John", and "Miami", respectively.


C# Nested Anonymous Type

In C#, we can also create an anonymous type inside the property of another anonymous type. This is called nested anonymous type. For example,

using System;
class Program
{
    static void Main()
    {
        // create another anonymous type inside Employee property 
        var school = new
        {
            Address = "Orlando",
            Contact = 1200,
Employee = new { Id = 3, Name = "Tina" }
}; // access Address property Console.WriteLine(school.Address); // access Id property of Employee property Console.WriteLine(school.Employee.Id); } }

Output

Orlando
3

In the above example, notice the code

var school = new
{
    Address = "Orlando",
    Contact = 1200,
    Employee = new { Id = 3, Name = "Tina" }
};

Here, we have created an anonymous type variable school with properties: Address, Contact, and Employee. You can see that the Employee property itself is also an anonymous type.

This is an example of a nested anonymous type.

Also, we are using the dot operator to access properties of the nested anonymous type.

  • school.Address - accesses the Address property of school
  • school.Employee.Id - accesses the Id property which is present inside the Employee property

Features of Anonymous Type in C#

Some of the features of anonymous type in C# are:

  • It encapsulates a set of read-only properties.
  • It cannot contain method or events of a class.
  • It has local scope. This means, the anonymous type is accessible only from the class in which it is defined.
  • We can create an array of anonymous types.
  • We can retrieve specific properties of anonymous type using LINQ.

Frequently Asked Questions

Can anonymous types contain methods?

No, the anonymous types cannot contain methods. For example,

using System;
class Program
{
    static void Main()
    {
        // create an anonymous type containing 3 properties 
        var person = new
        {
// throws error since we can't define a method // inside anonymous type static void MyMethod() { Console.WriteLine("..."); }
}; // display the anonymous type Console.WriteLine(person); } }

This throws an error.

Can we change properties inside the anonymous type?

No, we cannot change properties inside the anonymous type. Changing the value of property throws an error. For example,

using System;
class Program
{
    static void Main()
    {
        // create an anonymous type containing 3 properties 
        var person = new { Age = 34, Name = "John", Address = "Miami" };

// change the value of Age property person.Age = 36;
Console.WriteLine(person.Age); } }

Error:

Property or indexer '<anonymous type: int Age, string Name, string Address>.Age' cannot be assigned to -- it is read only
How to create an array of anonymous types?

We can create an array of anonymous types as

using System;
class Program
{
    static void Main()
    {
// create an array of anonymous type var employee = new[] { new{ID = 1, Name = "Jack"}, new{ID = 2, Name = "Jim"}, };
// access second element of the employee array using index Console.WriteLine("Second element of employee array is: " + employee[1]); // access the Name property of second anonymous type Console.WriteLine("Name property of second anonymous type is: " + employee[1].Name); } }

Output

Second element of employee array is: { ID = 2, Name = Jim }
Name property of second anonymous type is: Jim

In the above example, notice the code,

// create an array of anonymous type 
var employee = new[]
{
    new{ID = 1, Name = "Jack"},
    new{ID = 2, Name = "Jim"},
};

Here, we have created an array named employee using []. The employee array contains anonymous types as it's elements.

Here,

  • employee[1] - accesses element located at index 1 of array
  • employee[1].employeeName - accesses employeeName property of second anonymous type
How to retrieve specific properties of an anonymous type in LINQ?

We can use an anonymous type in LINQ which basically retrieves a subset of properties from every object of a collection. For example,

using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
    // define a class that contains three members 
    class car
    {
        public int Model;
        public string Name;
        public int Rating;
    }
    static void Main()
    {
        // create a list of car type 
        List<car> carInfo = new List<car>(){
            new car(){Model = 43, Name = "BMW", Rating = 4},
            new car() {Model = 23, Name = "Suzuki", Rating = 3},
        };

// select specific properties from carInfo var result = from c in carInfo select new { c.Model, c.Name };
// iterate through every items of present in result foreach (var items in result) { Console.WriteLine(items.Model + "-" + items.Name); } } }

Output

43-BMW
23-Suzuki

In the above example, carInfo is a list whose objects contain anonymous types. Notice the code below,

List<car> carInfo = new List<car>(){
            new car(){Model = 43, Name = "BMW", Rating = 4},
            new car() {Model = 23, Name = "Suzuki", Rating = 3},
        };

You can see in the code below that we have selected Model and Name properties from the carInfo list using a select clause:

// select specific properties from carInfo
var result = from c in carInfo
             select new { c.Model, c.Name };

Also, iterating through the result variable using foreach displays the specific properties that we have selected.

Did you find this article helpful?