How to call a generic method using a Type variable obtained at runtime?
Hello everyone! I'm writing a C# application and I've run into a problem that I haven't been able to solve for several hours. I have a generic method that accepts any data type and performs some logic with it, such as serialization. It looks like this:
```csharp
public T Deserialize(string jsonData)
{
return JsonSerializer.Deserialize(jsonData);
}
```
The problem is that the type I want to call this method with is only known **at runtime** — it's stored in a variable `Type myType`. For example, I load an assembly, find classes in it, and want to deserialize JSON for each of them, but I only know the type as a `Type` object.
I tried doing this:
```csharp
Type myType = typeof(MyClass); // I get this dynamically
var result = Deserialize(jsonString); // Error
No answers yet.
Log in to leave an answer
Blogs