Anonymous Classes in C#
Anonymous class was introduced in C# 2.0. It provides us with the ability to create new types ‘on the fly’ using Anonymous Types. Anonymous Types are essentially compiler generated types that you don’t explicitly declare with an official type declaration. The type name is generated by the compiler and is not available at the source code level or our application cannot access it.
An Anonymous class is a class that does not have a name.It helps us to increase the readability and maintainability of applications by keeping the declarations of variables closer to the code that uses it.You can create an anonymous class using the new keyword and a pair of braces defining the fields and values that you want the class to contain like:
Student1 = new { Name="Rohit Shaw", Age="21", Roll="01" };
Now, you might be thinking that If you dont know the name of the class, how will you create an object of appropriate type and assign an instance of the class to it? There lies the main essence of Anonymous classes whose type cannot be known. . However we can declare it as variable by using the var keyword such as
var Student1 = new { Name="Rohit Shaw", Age="22", Roll="01" }
Now, we can access the fields of the anonymous class by using the dot(.) notation such as Student1.Name, Student1.Age , etc
Note that if you create two anonymous types that have the exact same type signature in the same assembly, the C# compiler is smart enough to consolidate the anonymous class definition and reuse that type. So if you have code like the following:
protected object AnonymousTypes() { var Student1 = new { Name="Rohit Shaw", Age="22", Roll="01" } var Student2 = new { Name="Abhik Mitra", Age="23", Roll="02" } }
We can also create an array of anonymous typed elements by combining an implicitly typed local variable and an implicitly typed array such as
var Student=new[]{new{Name ="Rohit",Age=21},new{Name="Shaw",Age=22}};
Shortcomings:
However, it has some interesting features, yet it has some shortcomings:
1. Anonymous types are scoped only to the currently executing method. Because the generated type is anonymous there’s no public name for the type that you can access. In other words you can’t instantiate the type directly on your own and you can’t reference the type outside of the method that created it.
2. Anonymous class’s fields must all be initialized.
3. Anonymous class cannot specify any methods
4. Anonymous classes can only contain public fields
Share the post "Anonymous Classes in C#"
- tweet