How to set value for property of an anonymous object?

Leo Vo picture Leo Vo · Jul 3, 2013 · Viewed 40.5k times · Source

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.

Answer

MarcinJuraszek picture MarcinJuraszek · Jul 3, 2013

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)