0

How do I determine the type parameter of a generic method dynamically if I have the Type object.

For example -

Type typeObject = dataTable.Columns[columnName].DataType;
List<typeObject> values = dataTable.SampleMethod<typeObject>(param1, param2);

How do I achieve this?

Diptarag
  • 133
  • 3
  • 11
  • Have you tried [`typeof`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/typeof) already? – Baksteen Apr 16 '18 at 10:06
  • 3
    You don't. Generics provide compile-time typing; your proposed `List` needs a dynamic type. You can create such generic lists [at runtime, of course](https://stackoverflow.com/q/232535/4137916), but it's usually worth asking if you're using the right approach when you find yourself in this predicament. For example, `object` is not a dirty word, nor is `dynamic`. – Jeroen Mostert Apr 16 '18 at 10:07
  • Maybe use a common base-interface or -class instead of the excact type? Depending on why you think you need this the answer may look different from what you expect. Your question is quite unspecific, we can´t determine what exactly you need as we don´t know your context. Voting to close. – MakePeaceGreatAgain Apr 16 '18 at 10:13
  • Simple: don't use generics if you have to store/pass a `Type`. If you have them already - then you are doomed to a `switch/case` or similar solution, because you'll have to route execution. – Sinatr Apr 16 '18 at 10:25

0 Answers0