0

I'm currently dealing with a requirement to a pass Class to a GenericMethod as T. But I get my className as string parameter. When I know the className at Compile time, I have no issue. But I'm struck passing the className as T to the GenericMethod when I receive the className in string parameter..

How can I pass the className as a Class to the GenericMethod ChildClass_1: ParentClass

public override void CallGenericMethod(string currentClassName)
{
   var type = Type.GetType(currentClassName);
   GenericMethod<type>(typeOf(type).Name);
}

ParentClass.cs

 public virtual void GenericMethod<type>(string className){
   console.WriteLine("Invoked ClassName");
 }

Could anyone please help me in resolving this problem. Thanks in advance

Vijay
  • 745
  • 2
  • 9
  • 25
  • Does this answer your question? [How do I use reflection to call a generic method?](https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method) – Charlieface Apr 23 '21 at 12:24
  • @Charlieface, will check and update the comment – Vijay Apr 23 '21 at 12:55

1 Answers1

0

You need to build generic method in runtime:

public void CallGenericMethod(string currentClassName)
{
    var type = Type.GetType(currentClassName);
    var methodInfo = GetType().GetMethod(nameof(GenericMethod));
    methodInfo.MakeGenericMethod(type).Invoke(typeOf(type).Name);
}

null safety is omitted

Dmitriy Korolev
  • 288
  • 1
  • 10