joydip_kanjilal
Contributor

How to use anonymous types in C#

how-to
Apr 13, 20206 mins
C#Microsoft .NETSoftware Development

Take advantage of anonymous types in C# to create and instantiate types that have read-only properties without having to declare the type beforehand

An anonymous type is a type that doesn’t have a name. You can use an anonymous type to encapsulate a set of read-only properties inside a single unit — and you don’t need to define the anonymous type beforehand. This article discusses what anonymous types are, why they are important, and how we can work with anonymous types in C#.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here

Create a console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create.

This will create a new .NET Core console application project in Visual Studio 2019. We’ll use this project in the subsequent sections of this article to illustrate how we can work with anonymous types in C#.

Understand anonymous types in C#

Essentially an anonymous type is a reference type and can be defined using the var keyword. You can have one or more properties in an anonymous type but all of them are read-only. In contrast to a C# class, an anonymous type cannot have a field or a method — it can only have properties.

You can access an anonymous type or its properties inside the method where the anonymous type has been defined. In other words, the accessibility of an anonymous type is limited to the scope where it has been defined.

Use an anonymous type in C#

Let’s now dig into some code. Consider the following anonymous type.

var author = new
{
  FirstName = "Joydip",
  LastName = "Kanjilal",
  Address = "Hyderabad, INDIA"
};

In the preceding code snippet, author is the name of an instance of an anonymous type created using the new keyword. (The name of the anonymous type itself is known only by the compiler.) This anonymous type contains three properties, namely FirstName, LastName, and Address. All of these properties are of the string type. Note that when working with an anonymous type, you do not have to specify the type of a property before initializing it.

You can use the following code snippet to access all three properties of the above anonymous type.

Console.WriteLine("Name: {0} {1}", author.FirstName, author.LastName);
Console.WriteLine("Address: {0}", author.Address);

Use a nested anonymous type in C#

Anonymous types can be nested as well. That is, you can have an anonymous type as a property inside another anonymous type. Here is an example that illustrates this.

var author = new
{
  FirstName = "Joydip",
  LastName = "Kanjilal",
  Address = new { City = "Hyderabad", Country = "INDIA"}
};

You can access the properties of this nested anonymous type as shown in the code snippet given below.

Console.WriteLine("Name: {0} {1}", author.FirstName, author.LastName);
Console.WriteLine("Address: {0}", author.Address.City);

The complete program is given below for your reference.

static void Main(string[] args)
{
  var author = new
  {
     FirstName = "Joydip",
     LastName = "Kanjilal",
     Address = new { City = "Hyderabad", Country = "INDIA"}
  };
  Console.WriteLine("Name: {0} {1}", author.FirstName, author.LastName);
  Console.WriteLine("Address: {0}", author.Address.City);
  Console.Read();
}

Use anonymous types with LINQ 

The Select clause in LINQ creates and returns an anonymous type as a result. The following code snippet illustrates this.

Consider the following class named Author.

public class Author
{
  public int Id { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

The following code snippet shows how you can create a list of authors.

IList<Author> authors =
new List<Author>()
{
  new Author() { Id = 1, FirstName = "John", LastName = "Willey"} ,
  new Author() { Id = 2, FirstName = "Steve", LastName = "Smith"} ,
  new Author() { Id = 3, FirstName = "Bill", LastName = "Ruffner"} ,
  new Author() { Id = 4, FirstName = "Joydip",  LastName = "Kanjilal" }
};

And the next code snippet shows how you can take advantage of the Select clause in LINQ together with an anonymous type to return the result upon execution of a query.

var result = from a in authors select new
{
   Id = a.Id,
   Name = a.FirstName + "t"+ a.LastName
};

You can now display the author Ids and names at the console window as shown in the code snippet below.

foreach (var data in result)
      Console.WriteLine(data.Name);

The complete program is given below for your reference.

public class Author
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            IList<Author> authors = new List<Author>() {
                        new Author() { Id = 1, FirstName = "John",
                                      LastName = "Willey"},
                        new Author() { Id = 2, FirstName = "Steve",
                                      LastName = "Smith"},
                        new Author() { Id = 3, FirstName = "Bill",
                                      LastName = "Ruffner"},
                        new Author() { Id = 4, FirstName = "Joydip",
                                      LastName = "Kanjilal"}
                };
            var result = from a in authors
                         select new
                         {
                             Id = a.Id,
                             Name = a.FirstName + "t" + a.LastName
                         };
            foreach (var data in result)
                Console.WriteLine(data.Name);
            Console.Read();
        }
    }

Anonymous types allow you to create a type and instantiate it quickly without having to declare the type earlier. From the CLR’s point of view, an anonymous type is just another reference type. The compiler provides a name to each anonymous type under the covers.

Anonymous types derive from the Object class. This is why you can cast an anonymous type only to an instance of Object type. Note also that the return type of a method, a property, an event, a delegate, etc. cannot be an anonymous type.

How to do more in C#:

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author