1

I'm trying to figure out a way to pass a type into a generic function by only knowing the type name.

public void Main()
{
    string typeName = "string";
    Test<typeName>();
}

public void Test<T>()
{
    // Do Work
}
user3953989
  • 1,844
  • 3
  • 25
  • 56
  • @Steve Is there a way to do this without having to use reflection to invoke the generic method? – user3953989 Oct 25 '16 at 01:48
  • 1
    Not that I'm aware of, Reflection is needed because you don't know the type at compile time. – Steve Oct 25 '16 at 01:49
  • This might be an XY problem. Why do you have type names in string format? If it's only a few specific types, the absolute simplest would be to initialize a dictionary with the string names as keys and the types as values. But... that's about the worst way to solve this, haha. – Zach Mierzejewski Oct 25 '16 at 01:52
  • @ZachMierzejewski I'm trying to create a generic RESTful web api. The webroute is /type/id and the method will have the type name as a string param. From there I can do "return repository.Get(id);" This way I do not have 30 methods with identical code and only a different type – user3953989 Oct 25 '16 at 01:55
  • @ZachMierzejewski Not sure I follow, yourObject will always be a string. And I can create a Type type from the string name but that can't be used as a generic param – user3953989 Oct 25 '16 at 02:00
  • @user3953989 Yeah, I deleted my comment after I reread your question. I don't think that "duplicate" will help you. I'll keep looking. – Zach Mierzejewski Oct 25 '16 at 02:03
  • [How to get class type from string.](https://stackoverflow.com/questions/1044455/c-sharp-reflection-how-to-get-class-reference-from-string) – Zach Mierzejewski Oct 25 '16 at 02:04

0 Answers0