What is Anonymous Types in C#?
Last Updated :
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.
Anonymous-Types-in-C-Sharp
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:
CSharp
// C# program to illustrate how a
// method accept anonymous type as
// a parameter using dynamic type
using 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:
CSharp
// C# program to illustrate the
// concept of anonymous types
using 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);
}
}
Output:
Student id: 109
Student name: Sohan
Language: C#
Nested Anonymous Type
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:
CSharp
// C# program to illustrate the concept
// of nested anonymous types
using 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 = "[email protected]"}};
// 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);
}
}
Anonymous type in LINQ
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:
CSharp
// C# program to illustrate the
// concept of anonymous type in LINQ
using 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();
}
}
}
Output:
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#
Similar Reads
Anonymous Method in C#
An anonymous method is a method which doesnât contain any name which is introduced in C# 2.0. It is useful when the user wants to create an inline method and also wants to pass parameter in the anonymous method like other methods. An Anonymous method is defined using the delegate keyword and the use
3 min read
What is Reflection in C#?
Reflection is the process of describing the metadata of types, methods and fields in a code. The namespace System.Reflection enables you to obtain data about the loaded assemblies, the elements within them like classes, methods and value types. Some of the commonly used classes of System.Reflection
4 min read
Is vs As operator keyword in C#
The difference between is and as operators are as follows: The is operator is used to check if the run-time type of an object is compatible with the given type or not whereas as operator is used to perform conversion between compatible reference types or Nullable types. The is operator is of boolean
3 min read
C# | Implicitly Typed Arrays
Implicitly typed arrays are those arrays in which the type of the array is deduced from the element specified in the array initializer. The implicitly typed arrays are similar to implicitly typed variable. In general, implicitly typed arrays are used in the query expression.Important points about im
3 min read
Binary Literals and Digit Separators in C#
Binary Literals The fixed values are called as Literal. Literal is a value which is used by the variables. Before C# 7.0 six types of literals are available that are an integer, Floating-point, Character, String, Null, Boolean literals. In C# 7.0 there is one more literal is added which is known as
2 min read
List BinarySearch() Method in C#
List<T>.BinarySearch(T) Method uses a binary search algorithm to locate a specific element in the sorted List<T> or a portion of it. There are 3 methods in the overload list of this method as follows:BinarySearch(T)BinarySearch(T, IComparer<T>)BinarySearch(Int32, Int32, T, ICompare
9 min read
Type System Unification in C# .NET
The Type System Unification in C# means all the data types in C# are inherited from the Object class, whether directly or indirectly. Or you can say all types are considered as objects. In C#, primitive types are known as the Value Types which are basically structs. Internally, structs and classes i
3 min read
Type.FindInterfaces() Method in C# with Examples
Type.FindInterfaces(TypeFilter, Object) Method is used to return an array of Type objects which represents a filtered list of interfaces implemented or inherited by the current Type. All of the interfaces implemented by this class are considered during the search, whether declared by a base class or
3 min read
Type.GetConstructors() Method in C# with Examples
Type.GetConstructors() Method is used to get the constructors of the Type object. There are 2 methods in the overload list of this method as follows: Type.GetConstructors() Method This method is used to returns all the public constructors defined for the current Type.Syntax: public System.Reflection
4 min read
C# | Deconstructors with Tuples
A tuple is a data structure which gives you the easiest way to represent a data set which has multiple values that may/may not be related to each other. But if you are trying to retrieve multiple fields or property values from the tuple is more difficult. So, to overcome this problem deconstructor w
6 min read