Anonymous type property name inference

How anonymous types can infer property names from variable names

Home DailyDrop

Daily Knowledge Drop

When creating an anonymous type and setting properties based on other variables, the name of the property can be inferred from the name of the variable setting the property.


Example

Below is a very simple example:

int Age = 45;
string Name = "John Doe";

var anonType = new
{
    Age,
    Name
};

Console.WriteLine(anonType);

Here, two variables (one int and one string) are being declared with values. An anonymous type is then being declared, using the two variables - without the name of the properties being set.

The output is as follows:

    { Age = 45, Name = John Doe }

The anonymous type inferred the name of the properties from the variable names.


The names can also be explicitly set if the name of the variable isn't meaningful:

int Age = 45;
string str_col1 = "John Doe";

var anonType = new
{
    Age,
    FullName = str_col1 // Property name explicitly set
};

Console.WriteLine(anonType);

Now the name of the property is not inferred:

    { Age = 45, FullName = John Doe }

The name inference also works with more complex types (such as classes, and other anonymous types):

int Age = 45;
string Name = "John Doe";

var anonType = new
{
    Age,
    FullName = Name
};

var AnotherAnonType = new
{
    anonType,
    Index = 0
};

Console.WriteLine(AnotherAnonType);

With the output now being:

    { anonType = { Age = 45, FullName = John Doe }, Index = 0 }

Notes

When working with anonymous types, ensure to name variables accurately and meaningfully. The ability to automatically infer the anonymous type property names will save on additional type, and unnecessary code as well as make the code naming standards more consistent.


References

StackOverflow comment

Daily Drop 76: 18-05-2022

At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.

The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.
c# .net anonymous inference