cllpse
cllpse

Reputation: 21727

Is is possible to implement setters on properties of anonymous types

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

Answers (2)

Johannes Rudolph
Johannes Rudolph

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:

  • Use Tuples instead of annonymous types. Note that they are immutable too but you can work with them more easily to create methods like tupleA.WithItem2(newValueForItem2). Similar to the string class.
  • write your own "named" type using auto properties, usually straightforward
  • use a refactoring tool like CodeRush that can generate a "named" type from your usage

Upvotes: 3

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

No, cause anonymous types in C# are immutable by design.

Upvotes: 7

Related Questions