Stécy
Stécy

Reputation: 12339

How to instantiate a subtype inside a dynamic class?

I'm using C# dynamic keyword and I've got an instance where I need to set a property value.

However, this property requires a type that I have no access to since I generated an assembly in memory from WSDL.

How can I create the property instance dynamically?

Upvotes: 0

Views: 192

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062780

There is no such thing as a property instance; there is:

  • an instance of an object
  • which has members (which may be dynamic in this case)
  • to which you want to assign a value

If you don't know the type of the value in advance, you will need to create the object with a combination of reflection (from the Type) and perhaps dynamic. The latter depends on whether the underlying object is actually dynamic, vs being a regular type exposed via the dynamic API. Likewise, whether you can assign the value to the property via reflection - or whether you must use the dynamic API - depends on the same. Fortunately, there are tools like FastMember which allow you to access arbitrary members (with names known only at runtime, not compile-time) identically for the two cases. So if the scenario is complex, maybe give that a whirl.

Upvotes: 1

Related Questions