Reputation: 21727
Consider the following:
var o = new { Foo = "foo", Bar = "bar" };
This instance is read-only, since the anonymous type doesn't implement setters like a class does:
public class O
{
public String Foo { get; set; }
public String Bar { get; set; }
}
Is it possible to "open up" the anonymous instance and allow it's properties to be altered? Preferably in fewer characters than it would take to create a class.
I'm thinking perhaps this can be done with an extension method on Object; o.SetProperty(o.Foo, "foo!");
, if you can't implement setters in-line at the construction of the object.
Upvotes: 1
Views: 708
Reputation: 35731
Anonymous types are immutable by design, so there's no way you can change their state. You could use reflection (as Mark Gravell pointed out correctly) but neither is this desirable performance wise nor from a design perspective.
You've got multiple options to work around this:
tupleA.WithItem2(newValueForItem2)
. Similar to the string
class.Upvotes: 3
Reputation: 116401
No, cause anonymous types in C# are immutable by design.
Upvotes: 7