Question

I was wondering if it is possible to use Reflection or something else to call a constructor in a method by having the className passed as string to the method. This is done in the context of interpretation of commands. Trying to avoid switch statements (I have some weird assignments at school and I am looking for a shortcut for my exams).

    Class SomeClass
    {
      //irrelevant code here 

      public BaseClass SomeMethod(string constructorName)
      {
       //call constructor here through string parameter to avoid switch statements
       //for example string constructorName=SomeDerivedClassName
       // and the result should be:
       return SomeDerivedClassName(this.SomeProperty,this.SomeOtherPropertY);
      }

    }
Was it helpful?

Solution

Try something like:

class SomeClass
{
  //irrelevant code here 

  public BaseClass SomeMethod(string constructorName)
  {
    // possibly prepend namespace to 'constructorName' string first

    var assemblyToSearch = typeof(SomeClass).Assembly;
    var foundType = assemblyToSearch.GetType(constructorName);

    return (BaseClass)Activator.CreateInstance(foundType,
      this.SomeProperty, this.SomeOtherPropertY);
  }
}

Of course if the class can be in different assemblies, modify the code accordingly.

This assumes the constructor in question is public.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top