How can I pass a generic method type parameter as a variable to it? Below given is the crud example of what I want to achieve. It's just for a demo purpose, not the actual code. I can use if...else
or switch
to go through passed category and call generic method with corresponding type parameter.
[HttpGet]
[Route("{category}")]
public IActionResult Get(string category)
{
object data = new object();
string json = GetData(category);
if (category == "User")
{
data = JsonConvert.DeserializeObject<User>(json);
}
else if (category == "Organization")
{
data = JsonConvert.DeserializeObject<Organization>(json);
}
return Ok(data);
}
Assume GetData
is a function which gives me a collection in a JSON format based on passed category. I want to call a generic method, DeserializeObject<T>(...)
, which requires a type parameter. The class which refers the type parameter is related to passed category. How to achieve like given below?
[HttpGet]
[Route("{category}")]
public IActionResult Get(string category)
{
string json = GetData(category);
T categoryType = GetCategoryType(category); // what should be here???
object data = JsonConvert.DeserializeObject<categoryType>(json);
return Ok(data);
}