C# Anonymous Types

In c#, anonymous types are useful to create an object that contains a set of read-only properties without specifying its type using the new keyword. The name and type for the properties in anonymous type object will be generated by the compiler automatically.

 

Generally, the reference of anonymous types can be held by var type variables. So, we need to declare the variable by using the var keyword to assign anonymous objects.

 

Following is the example of creating an anonymous type object with a set of properties in c#.

 

var userInfo = new { Id = 1, name = "Suresh", isActive = true };

If you observe the above code, we created an anonymous type object with three properties using new keyword and assigned the object to the variable (userInfo) which is defined with the var keyword.

 

Here, we need to remember one thing that the expression which we used to assign a value to the property in the anonymous type object cannot be null.

 

As we discussed, the compiler will automatically assign the name and type for the properties in anonymous type object. If you check the following image, when we try to access the properties of an anonymous object, the compiler automatically generated a new name for the anonymous type and applied the appropriate type for the properties based on the value expressions.

 

C# Access Anonymous Type Properties

 

The compiler has assigned int type for Id, string type for Name and bool type for IsActive property based on the values which we assigned to respective properties.

C# Anonymous Type Example

Following is the example of defining and accessing the properties of an anonymous object in c#.

 

using System;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            // Create anonymous type object

            var userInfo = new

            {

                Id = 1,

                Name = "Suresh Dasari",

                IsActive = true

            };

            // Access anonymous type object properties

            Console.WriteLine("Id:" + userInfo.Id);

            Console.WriteLine("Name:" + userInfo.Name);

            Console.WriteLine("IsActive:" + userInfo.IsActive);

            Console.ReadLine();

        }

    }

}

When we execute the above code, we will get the result like as shown below.

 

Id: 1

Name: Suresh Dasari

IsActive: True

C# Anonymous Type Access Scope

In c#, the access scope of anonymous type is limited to the method where it has defined. In case, if we want to send the anonymous type to another method, then that method must accept the parameter of dynamic type but that is not recommended.

 

Following is the example of declaring and sending anonymous type as a parameter to another method using dynamic type in c#.

 

using System;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            // Create anonymous type object

            var userInfo = new { Id = 1, Name = "Suresh Dasari", IsActive = true };

            // Sending anonymous type object as parameter

            GetDetails(userInfo);

            Console.ReadLine();

        }

        static void GetDetails(dynamic user)

        {

            Console.WriteLine("Id:" + user.Id);

            Console.WriteLine("Name:" + user.Name);

            Console.WriteLine("IsActive:" + user.IsActive);

        }

    }

}

If you observe the above example, we are sending an anonymous type object (userInfo) as a parameter to the method (GetDetails) that accepts a parameter of the dynamic type.

 

When we execute the above example, we will get the result like as shown below.

 

Id: 1

Name: Suresh Dasari

IsActive: True

C# Nested Anonymous Types

In c#, the nested anonymous types can be achieved by defining the anonymous type within another anonymous type as a property.

 

Following is the example of defining the nested anonymous types in c#.

 

using System;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            // Create Nested anonymous type object

            var user = new

            {

                Id = 1,

                Name = "Suresh Dasari",

                IsActive = true,

                jobInfo = new { Designation = "Lead", Location = "Hyderabad" }

            };

            // Access anonymous type object properties

            Console.WriteLine("Id: " + user.Id);

            Console.WriteLine("Name: " + user.Name);

            Console.WriteLine("IsActive: " + user.IsActive);

            Console.WriteLine("Designation: {0}, Location: {1}", user.jobInfo.Designation, user.jobInfo.Location);

            Console.ReadLine();

        }

    }

}

If you observe the above example, we defined an anonymous type object within another anonymous type object as a parameter to achieve nested anonymous type functionality.

 

When we execute the above example, we will get the result like as shown below.

 

Id: 1

Name: Suresh Dasari

IsActive: True

Designation: Lead, Location: Hyderabad

This is how we can achieve nested anonymous type functionality in c# based on our requirements.

C# Anonymous Types in LINQ

In c#, anonymous types are mostly useful in Select clause of LINQ query expressions to return the subset of properties from the defined object based on our requirements.

 

Following is the example of defining anonymous types in Select clause of LINQ query expression in c#.

 

using System;

using System.Collections.Generic;

using System.Linq;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            List<Student> sInfo = new List<Student>(){

            new Student() { Id = 1, Name = "Suresh", Marks = 300 },

            new Student() { Id = 2, Name = "Rohini", Marks = 500 },

            new Student() { Id = 3, Name = "Madhav", Marks = 400 },

            new Student() { Id = 4, Name = "Sateesh", Marks = 750 },

            new Student() { Id = 5, Name = "Praveen", Marks = 350 },

            new Student() { Id = 6, Name = "Sudheer", Marks = 450 },

            new Student() { Id = 7, Name = "Prasad", Marks = 650 }

            };

            var result = from s in sInfo  

                               select new { StudentName = s.Name, StudentMarks = s.Marks };

            Console.WriteLine("********** Result **********");

            foreach (var item in result)

            {

                Console.WriteLine("Name: {0}, Marks: {1}", item.StudentName, item.StudentMarks);

            }

            Console.ReadLine();

        }

    }

    class Student

    {

        public int Id { get; set; }

        public string Name { get; set; }

        public int Marks { get; set; }

    }

}

If you observe the above example, we created a class called Student with different properties and in Main() method, we created anonymous type object in LINQ Select query expression to return only the required fields in result set.

 

When we execute the above example, we will get the result like as shown below.

 

C# Anonymous Types with LINQ Query Example Result

 

In c#, while creating anonymous type object we must need to provide the name for a property that is being initialized with an expression. In case, if we don’t specify the field names in LINQ Select query expression while creating an anonymous type, then the compiler will automatically consider the same name as the property being used to initialize them like as shown below.

 

var result = from s in sInfo

                   select new { s.Name, s.Marks };

foreach (var item in result)

{

Console.WriteLine("Name: {0}, Marks: {1}", item.Name, item.Marks);

}

 To learn more about LINQ query expressions, refer LINQ Tutorial.

C# Anonymous Type Overview

Following are the important points which we need to remember about anonymous type in c#.

 

  • In c#, anonymous types are useful to create an object that contains a set of read-only properties without specifying its type using the new keyword.
  • In an anonymous type, the expression that is used to initialize a property cannot be null.
  • The reference of anonymous types can be held by implicitly typed variable var.
  • The access scope of the anonymous type is limited to the method where it has defined.
  • In c#, anonymous types are mostly useful in Select clause of LINQ query expressions.
 
 
 

Topics Covered