0

I need to call a function with the prototype:

SomeFunc<T>()

and say I have a class of:

public class Person
{
}

I would call it as SomeFunc<Person>(). However I only have Person expressed as a string so for instance:

var classString = "Person";

So how do I convert classString so I can pass it for T?

TheEdge
  • 9,291
  • 15
  • 67
  • 135
  • A combination of `Type.GetType()` (or `Assembly.GetType()`), and `MethodInfo.CreateGenericMethod` – canton7 Mar 05 '19 at 10:54
  • 1
    My question is: Can you rewrite your code to use a real class-type instead of a string? – Jannik Mar 05 '19 at 10:55
  • 2
    what is strange is that you want to call a method expecting a generic (which is determined at compile time) with a parameter determined at runtime. Are you sure generics are what you are looking for? – meJustAndrew Mar 05 '19 at 10:58
  • @himbrombeere that question supposes we have a `Type` object, which we don't here. And anyway, OP probably shouldn't be doing what they think they want to do – AakashM Mar 05 '19 at 11:06
  • @AakashM While I agree, I don´t think we should reopen this question, as it would be too broad anyway - we simply don´t know exactly why OP wants this. We **could** reopen if we knew. – MakePeaceGreatAgain Mar 05 '19 at 11:09
  • The reason I have the string is that it is in a stream of data sent to me. From said string I need to decode some subsequent bytes that represent that class type. – TheEdge Mar 05 '19 at 11:14

2 Answers2

0

You can get the type like this

var classString = "Person";
Type typeValue = Type.GetType(classString );
var type = type.AssemblyQualifiedName;

then call the function like this type

Haven't tried, but it should work

Akbar Badhusha
  • 2,415
  • 18
  • 30
  • 1
    `GetType` will need a complete assembly-qualified name for your own types in another assembly. Simply passing `"Person"` will therefor not work. Apart from this your answer is only a small part of the actual solution, leaving everything related to the generic method asside. – MakePeaceGreatAgain Mar 05 '19 at 10:56
  • @HimBromBeere that's not true? https://dotnetfiddle.net/dmgkUw – canton7 Mar 05 '19 at 10:58
  • 1
    @HimBromBeere if the type you're after is internal to the same assembly then you don't need the bells and whistles. Otherwise you would. We don't actually know where OP is trying to assign the type from – Michael Mar 05 '19 at 11:30
-1

See Andrew & Jon's answers on this question.

C# Reflection: How to get class reference from string

Someone should probably mark this as duplicate.

Michael
  • 810
  • 6
  • 18