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 What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos