user565869
user565869

Reputation:

How can I get a constructor for a type when one of the parameters is dynamic?

I have a series of classes with this constructor:

MyClass(Reader reader, dynamic json)  { ... }

I need to instantiate objects in a generic method. To do so I tried to get the constructor thuswise:

class Reader
...
T  Get<T>(string id)
    {
    dynamic  json        = GetData(id);
    var      constructor = typeof(T).GetConstructor(new Type[] { typeof(Reader), typeof(dynamic) });
    return constructor.Invoke(new object[] { this, json });
    }

However, neither dynamic nor typeof(dynamic) is acceptable in this circumstance. What's the appropriate way to do so? The constructor certainly does exist. There does not seem to be a binding flag for this situation.

For the moment, I've created a dead-simple JsonWrapper class as a workaround:

class JsonWrapper
{
JsonWrapper(dynamic json) { Json = json; }
dynamic  Json  { get;  private set; }
}
...
var  constructor = typeof(T).GetConstructor(new Type[] { typeof(Reader), typeof(JsonWrapper) });

I could also call GetConstructors() and take the first entry, as these classes only have the one - but that would be fragile.

Upvotes: 2

Views: 231

Answers (1)

AlexD
AlexD

Reputation: 32596

However, neither dynamic nor typeof(dynamic) is acceptable in this circumstance.

Consider using typeof(object) instead of typeof(dynamic).

MSDN says about dynamic that

In most cases, it functions like it has type object.

In particular, the following code fails with error "Type '....JsonWrapper' already defines a member called 'JsonWrapper' with the same parameter types"

public class JsonWrapper
{
    public JsonWrapper(dynamic json) { }
    public JsonWrapper(object json) { }
}

Upvotes: 3

Related Questions