0

I am just re-referencing to an earlier post as I could not quite get the issue resolved. C# convert string to class that has a constructor with string parameter

I have a loop in which I am trying to convert given strings into class types and instantiate them. Those classes have constructors with a string type parameter, which is a connection string to a database.

Up to this point seems OK. ExampleClass1, ExampleClass2, ExampleClass3...

Type type = Type.GetType("ExampleClass1");
object instance = Activator.CreateInstance(type, "connection_string_param");

However, when I try to access the class methods via the instance.DoSomething() I receive an error - object does not contain a definition for DoSomething.... When I instantiate the class regular way, I can see the class methods. Arturo Menchaca was suggesting to cast, appreciate his help earlier on, but casting the 'object' type into 'specific class type' would not work if the class type is not known yet. If I try (type)instance, it does not work... Any help is appreciated.

Community
  • 1
  • 1
user2217057
  • 237
  • 3
  • 17
  • The whole point of static typing is that the compiler can at least verify the correctness of your data types using static information. Clearly you don't have static type information here. So what would the compiler verify? (And what would it emit?) On the other hand, if you want to skip type checks altogether and delegate overload resolution to the runtime type, just use `dynamic` instead of `object`. – Theodoros Chatzigiannakis May 10 '16 at 20:48
  • 2
    Most likely you just need to read a bit about what interface is, then implement some interface for your classes. – Evk May 10 '16 at 20:49
  • http://stackoverflow.com/questions/7598088/purpose-of-activator-createinstance-with-example – Matt Rowland May 10 '16 at 20:50
  • Thanks for your suggestions, I cannot use interfaces approach here, or class hierarchies, as the class types are generated by Entity Framework. – user2217057 May 10 '16 at 20:52

1 Answers1

2

DoSomething() is not defined on object. It is defined on your ExampleClass1, and so on.

You can make it a dynamic object and call it directly:

dynamic instance = Activator.CreateInstance(type, "connection_string_param");
instance.DoSomething();

Or, invoke it by reflection :

object instance = Activator.CreateInstance(type, "connection_string_param");
instance.GetType().GetMethod("DoSomething").Invoke(instance, null);

However, you should reconsider your design, as this is not a good idea to do...

Xiaoy312
  • 14,292
  • 1
  • 32
  • 44