Take advantage of anonymous types in C# to create and instantiate types that have read-only properties without having to declare the type beforehand Credit: Vincent Diamante 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. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed. Click Next. In the “Configure your new project” window shown next, specify the name and location for the new project. 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#: When to use an abstract class vs. interface in C# How to work with AutoMapper in C# How to use lambda expressions in C# How to work with Action, Func, and Predicate delegates in C# How to use the Dapper ORM in C# How to implement a simple logger in C# How to work with log4net in C# How to work with delegates in C# How to work with attributes in C# How to use the flyweight design pattern in C# How to implement the repository design pattern in C# Exploring virtual and abstract methods in C# How to work with reflection in C# How to work with filesystemwatcher in C# Related content feature 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos