Reputation: 10604
I have a method that takes a generic type, performs a rest query against an API and returns a serialized object.
It works great, but, I want to extend this in order to create dynamic objects when calling APIs that there isn't a predefined type.
I have this working with the only change being a custom deserializer, however, I had to basically copy/paste my method with a different name as I couldn't work out a way of detecting the type as dynamic.
A little example:
public T PerformQuery<T>()
{
var deserializer = new JsonDeserializer();
var res = deserializer.Deserialize<T>(response);
return res;
}
public Dynamic PerformQueryDynamic()
{
var deserializer = new DynamicJsonDeserializer();
var res = deserializer.Deserialize<T>(response);
return res;
}
What I would like:
public T PerformQuery<T>()
{
if(Typeof(T) == Typeof(Dynamic))
var deserializer = new DynamicJsonDeserializer();
else
var deserializer = new JsonDeserializer();
var res = deserializer.Deserialize<T>(response);
return res;
}
I've read other posts here and I understand why Typeof doesn't work with Dynamic, but, I was wondering if there is anything that can do what I want here? There are other things in this method such as Oauth calls and similar that would be so much neater if I can keep this as one method.
... Failing a solution, I was thinking of just adding a bool to the constructor, but, seems like a waste if there is an answer.
Upvotes: 2
Views: 84
Reputation: 51330
There is no dynamic
type. It's all syntactic sugar around dynamic call sites. The compiler will replace dynamic
with object
underneath.
As I suppose deserializing an object
(which has no fields) is meaningless, you could work around this by using:
public T PerformQuery<T>(string response)
{
if (typeof(T) == typeof(object))
return new DynamicJsonDeserializer().Deserialize<T>(response);
return new JsonDeserializer().Deserialize<T>(response);
}
So PerformQuery<object>
will work the same as PerformQuery<dynamic>
, but like I said, this shouldn't be an issue.
Upvotes: 2