Rules for using Anonymous Types in C#

The anonymous types (var) in C# is an interesting feature that the C# developers could use within their .NET application . When using the anonymous type , there are certain criteria or rules that needs to be followed .

Rules for using Anonymous Types in C#

Below are some of the rules that the developers should be following when using the anonymous type.

1. NULL value cannot be assigned to the anonymous type. When you try doing that , you will receive the following error “Error    CS0815    Cannot assign <null> to an implicitly-typed variable”.

2. Anonymous type cannot be used for the class member or fields.

3. Anonymous types are also derived from the Object type.

4. You cannot have the anonymous type as the return type of a method.

image

5. You cannot have the anonymous type as the parameter for a method.

6. The anonymous type or implicit type variable has to be initialized when declared.