mercredi 8 novembre 2023

Get a dictionary of a generic type based on a runtime value

I wish to declare a dictionary based on a runtime type. So, instead of doing this:

IEnumerable dict = null;
if(type == typeof(SomeType)) dict = new Dictionary<SomeType, string>()
if(type == typeof(SomeOtherType)) dict = new Dictionary<SomeOtherType, string>()

I wish to do something like this:

IEnumerable dict = new Dictionary<type, string>();

How can I achieve this? Also, I would like to be able to call a different method with just the type of the dictionary in one of these ways:

var result = SomeMethod(typeof(Dictionary<type, string>));
var result = SomeMethod<Dictionary<type, string>>();

EDIT: extra context:

I get the types from a different API call as strings. Then I use reflection to get the types by AssemblyQualifiedName, which results in a List to execute the calls with. Based on the name of these types, REST endpoints need to be called.

If (type == SomeType) httpClient.GetAsync("SomePath/{SomeType.Name}")

This endpoint returns a Dictionary<SomeType, string>. To be able to deserialize these types, I need to call something like

httpClient.GetAsync<Dictionary<type, string>>("SomePath/{SomeType.Name}")

Otherwise an exception will occur in the System.Text.Json package.





Aucun commentaire:

Enregistrer un commentaire