0

I am trying to call a method that changes the Type at runtime. And I am using the data from the HTTP request to extract the name of the Type. For example.

If the http request is /pets/Dog then I am using the Dog as the type for my getData call. For example

var data = await dbAccessor.GetData<Dog>(id)

And if the URL was /pets/Cat then my method call will be as follows

var data = await dbAccessor.GetData<Cat>(id)

But I am getting the error that says "Cannot await 'method group' ", does anyone know what this means? Below is how my method is defined.

public async Task<SomeModel<AnotherModel>> GetId (string id) {
// this.x.y will extract the name from request
var data = await dbAccessor.GetData<this.x.y>(id);
}
  • generics require compile-time types. – David L Oct 26 '22 at 18:55
  • `this.x.y` is not a type. To do what you want, you need to know the type at compile time. If you want to do what you want, you should overload with an implementation of `GetData(Type type, string id);` – Neil Oct 26 '22 at 18:56
  • 2
    `GetData` is a generic method that takes a type; `this.x.y` is not a type. If you need to call a generic method with a type known only at runtime, see [this question](https://stackoverflow.com/q/232535/4137916). Note that it is a very bad idea to extract type names from unverified user input, as this potentially enables instantiation of arbitrary types, which could have nasty effects. You're better off using a `switch` or dictionary lookup to only accept *specific* type names (a dictionary can then still be filled dynamically at runtime, if you so prefer, but only with DTO types). – Jeroen Mostert Oct 26 '22 at 18:56
  • @JeroenMostert Do you have any examples of how I can use a dictionary and fill it up dynamically with the types that I want? – HackerMan33453 Oct 26 '22 at 19:06
  • 1
    You could mark classes with an attribute and [search for that](https://stackoverflow.com/q/607178/4137916), or apply a naming convention and check for that, or get the list of actual entity type names (as in, tables) from your DB layer (if it supports that). – Jeroen Mostert Oct 26 '22 at 19:10
  • https://learn.microsoft.com/en-us/dotnet/api/system.reflection.methodinfo.makegenericmethod?view=net-7.0 – Hans Passant Oct 26 '22 at 21:09

0 Answers0