#839 – Anonymous Type Limitations

An anonymous type is a temporary data type that is inferred based on the data that you include in an object initializer.

An anonymous type has a couple of  limitations.  Its only members are public, read-only properties.  The type can’t contain methods or other type members and you cannot write to its properties.

            var tt = new { Name = "Kirby", Age = 12 };
            tt.Name = "bob";   // Error - Name can't be assigned to

The anonymous type must be implicitly convertible to the type of a variable used to store the new object.  In other words, the variable must either be implicitly typed using the var keyword, or must be of type object.  You’ll almost always want to use the first option, since the resulting variable is still strongly typed.

Advertisements