Fred
Fred

Reputation: 4076

Dynamic class member?

Is it possible to use a dynamic class member? For example

class blarg
{
public dynamic ctx = new ExpandoObject();
}

without also making blarg inherit (and implement) from DynamicObject?

Upvotes: 0

Views: 717

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1064184

There is no fixed inheritance structure; firstly, dynamic can use reflection/meta-programming anyway, so you can just attach a regular class with members and it'll work - but you won't be able to add new members etc. Secondly, "all" you need to do to support full dynamic is implement IDynamicMetaObjectProvider - not inherit something. The "all" is in quotes, because that isn't trivial. DynamicObject exists to do some of the heavy lifting for you, as does ExpandoObject for the cases when you just want a property-bag.

But since the callers aren't binding to any particular type (since they are using dynamic), frankly it isn't a huge problem to inherit from DynamicObject.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564891

Yes. You can make a field or property dynamic within any class.

Inheriting from DynamicObject is only required (technically, you need to implement IDynamicMetaObjectProvider, but this is typically done via DynamicObject) if you want your class itself to be dynamic.

Upvotes: 2

Related Questions