What is Anonymous Types in C#? - GeeksforGeeks

13 May, 2019
Anonymous types in C# are the types which do not have a name or you can say the creation of new types without defining them. It is introduced in C# 3.0. It is a temporary data type which is inferred based on the data that you insert in an object initializer. Or in other words, an anonymous type provides an efficient way to combine a set of read-only into a single object without any explicit type. The type of the anonymous type is automatically generated by the compiler according to the value assigned to its properties. These are best for the “use and throw” types.
In the above image, we are creating anonymous types by using “new” keyword with the object initializer
Important Points:
It is derived from System.Object class and it is also a sealed class. So, the properties of anonymous type are read-only means you cannot change their values.
It also has intellisense support in Visual Studio.
It can contain one or more read-only properties.
It does not contain class members such as events, methods, etc.
The expression that used to initialize properties are not null, anonymous method, or a pointer type.
You can also create an anonymous type array.
It cannot be cast to any other type except an object.
It is of reference type.
You are not allowed to create a field, property, event, or return type of a method is of anonymous type.
You are not allowed to declare formal parameters of a method, property, constructor, indexer as a anonymous type.
The scope of the anonymous type is always limited to the method in which they are defined. Due to their local scope, you are not allowed to pass an anonymous type to another method, but you can pass it to those methods which can accept dynamic type parameters. As shown in the below example.Note: Generally, passing anonymous type using dynamic type is not recommended.Example:// C# program to illustrate how a // method accept anonymous type as // a parameter using dynamic typeusing System;  public class GFG {      // Anonymous type object is passed in the     // method which has dynamic type parameters    static public void mymethod(dynamic val)    {        Console.WriteLine(val.s_id);        Console.WriteLine(val.s_name);        Console.WriteLine(val.language);    }      // Main method    static public void Main()    {          // Anonymous type object        var anony_object = new {s_id = 134,                                 s_name = "Siya",                              language = "Ruby"};          // Calling mymethod        mymethod(anony_object);    }}Output:134
Siya
Ruby

Note: Generally, passing anonymous type using dynamic type is not recommended.
Example:
// C# program to illustrate how a // method accept anonymous type as // a parameter using dynamic typeusing System;  public class GFG {      // Anonymous type object is passed in the     // method which has dynamic type parameters    static public void mymethod(dynamic val)    {        Console.WriteLine(val.s_id);        Console.WriteLine(val.s_name);        Console.WriteLine(val.language);    }      // Main method    static public void Main()    {          // Anonymous type object        var anony_object = new {s_id = 134,                                 s_name = "Siya",                              language = "Ruby"};          // Calling mymethod        mymethod(anony_object);    }}
Output:
134
Siya
Ruby

In C#, you are allowed to create an anonymous type object with a new keyword without its class definition and var is used to hold the reference of the anonymous types. As shown in the below example, anony_object is an anonymous type object which contains three properties that are s_id, s_name, language.
Example:
// C# program to illustrate the// concept of anonymous typesusing System;  public class GFG {      // Main method    static public void Main()    {          // Creating and initializing anonymous object        var anony_object = new {s_id = 109,                                s_name = "Sohan",                                language = "C#" };          // Accessing the object properties        Console.WriteLine("Student id: " + anony_object.s_id);        Console.WriteLine("Student name: " + anony_object.s_name);        Console.WriteLine("Language: " + anony_object.language);    }}
Student id: 109
Student name: Sohan
Language: C#

In C#, an anonymous type can have another anonymous type as a property. The nested anonymous type has IntelliSense support in Visual Studio. As shown in the below example, anony_object is an anonymous type object which contains another anonymous type object that is anony_ob:
Example:
// C# program to illustrate the concept// of nested anonymous typesusing System;  public class GFG {      // Main method    static public void Main()    {          // Creating and initializing nested anonymous object        var anony_object = new {s_id = 149, s_name = "Soniya", language = "C#",                                anony_ob = new { email = "soniya45@gmail.com"}};          // Accessing the object properties        Console.WriteLine("Student id: " + anony_object.s_id);        Console.WriteLine("Student name: " + anony_object.s_name);        Console.WriteLine("Language: " + anony_object.language);        Console.WriteLine("Email: " + anony_object.anony_ob.email);    }}
Student id: 149
Student name: Soniya
Language: C#
Email: soniya45@gmail.com

You are allowed to use an anonymous type in LINQ. In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class. As shown in the below example, the Geeks class contains four properties that are A_no, Aname, language, and age. But in result we only need A_no, Aname, and language, so we use a select query which creates a result of an anonymous type which only contains A_no, Aname, and language.
Example:
// C# program to illustrate the // concept of anonymous type in LINQusing System;using System.Collections.Generic;using System.Linq;  class Geeks {      public int A_no;    public string Aname;    public string language;    public int age;}  class GFG {      // Main method    static void Main()    {        List<Geeks> g = new List<Geeks>         {              new Geeks{ A_no = 123, Aname = "Shilpa",                        language = "C#", age = 23 },            new Geeks{ A_no = 124, Aname = "Shilpi",                        language = "C#", age = 20 },            new Geeks{ A_no = 125, Aname = "Soniya",                         language = "C#", age = 22 },            new Geeks{ A_no = 126, Aname = "Sonaly",                         language = "C#", age = 25 },          };          // select query showing result        // using anonymous type        var anony_ob = from geek in g select new {geek.A_no, geek.Aname, geek.language};        foreach(var i in anony_ob)        {            Console.WriteLine("Author id = " + i.A_no + "\nAuthor name = "                                  + i.Aname + "\nLanguage = " + i.language);            Console.WriteLine();        }    }}
Author id = 123
Author name = Shilpa
Language = C#

Author id = 124
Author name = Shilpi
Language = C#

Author id = 125
Author name = Soniya
Language = C#

Author id = 126
Author name = Sonaly
Language = C#

Akanksha_Rai
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Lambda Expressions in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?