Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How are anonymous types different from other types?


Asked by Jazmin Montes on Dec 13, 2021 FAQ



Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object. The compiler provides a name for each anonymous type, although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type.
Accordingly,
If two or more anonymous object initializers in an assembly specify a sequence of properties that are in the same order and that have the same names and types, the compiler treats the objects as instances of the same type. They share the same compiler-generated type information.
In addition, The implicitly typed variable- var, is used to hold an anonymous type. Anonymous type is a reference type and all the properties are read-only. The scope of an anonymous type is local to the method where it is defined.
Also,
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.
Furthermore,
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.