-2

So I have a method that accepts an argument to provide the type, and I want to pass in this type into a deserialization of some data that I am getting back from Redis Cache. But it says "(variable name) is a variable but is used as a type". Does anyone know how to fix this?

protected async Task<BaseModel> GetData<T>(string id, Type modelType) {

    var data = await this.cacheDatabase.StringGetAsync(key).ConfigureAwait(false);
    var response = JsonConvert.DeserializeObject<modelType>(data); // error here
    return response;

}

If I hardcode the model type in the deserialization, it works perfectly, but of course this is not ideal since I would like this method to handle various different model types. See below for the working code.

protected async Task<BaseModel> GetData<T>(string id) {

    var data = await this.cacheDatabase.StringGetAsync(key).ConfigureAwait(false);
    var response = JsonConvert.DeserializeObject<Dog>(data); // works fine as Dog is a child class of BaseModel.
    return response;

}
  • What's the point of the `T` generic argument? Why is that not used? – gunr2171 Nov 01 '22 at 22:50
  • 1
    I don't think this question is actually a duplicate of the one linked above. The accepted answer shows that the question had nothing to do with reflection. – TKharaishvili Nov 02 '22 at 20:56

1 Answers1

0

JsonConvert.DeserializeObject has an overload which accepts a value of type Type as a second argument. So you could try this:

var response = JsonConvert.DeserializeObject(data, modelType);

And there's no need for the T type parameter at all.

TKharaishvili
  • 1,997
  • 1
  • 19
  • 30
  • The problem is, I would need the function call to be dynamic too right? I don't know what that model used will be. It can be Dog, Cat, Goat, etc.. I have to get it dynamically from a variable. So for example, if the variable that holds the dynamic model type is named "test", then it would be GetData(id). But I am sure it will have the same error saying can't use test as it is a variable and not a type. @TKharaishvili – HackerMan33453 Nov 01 '22 at 23:01
  • @HackerMan33453 I've updated my answer. Hope it helps now – TKharaishvili Nov 01 '22 at 23:07
  • @HackerMan33453 I've edited my response to only contain the final answer. I think that's clearer for anyone who might come across it in the future. – TKharaishvili Nov 02 '22 at 20:54