Search code examples
c#.netanonymous-types

How to set value for property of an anonymous object?


this is my code for example:

var output = new
{
    NetSessionId = string.Empty
};

foreach (var property in output.GetType().GetProperties())
{
    property.SetValue(output, "Test", null);
}

It occurs an exception: "Property set method not found". I want to know how to create an anonymous type with properties which can be set.

Thanks.


Solution

  • Anonymous type properties are read only and they cannot be set.

    Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.

    Anonymous Types (C# Programming Guide)