1

I am new to C# and writing some automation framework .I want to initialize a class dynamically based on condition .

i get the name of the class as a string based on conditions . Ex : "Vehicle_"+ typeOfvehicle => Which will on run time may be Vehicle_2Wheeler or Vehicle_3Wheeler or Vehicle_4Wheeler .

I am using if , else statement for now . But if i can initialize the class with the type of Class i want to dynamically it would be better .

I think i need to use the Reflection API but not sure how to achieve this .

Please let me know if some one has an idea of this .

dandan78
  • 13,328
  • 13
  • 64
  • 78
SriSri
  • 95
  • 1
  • 13

1 Answers1

3

In C# Type.GetType("Truck") will return a Type that you can then instantiate

var type = Type.GetType("MyProject.Truck");
var instance = (Vehicle)Activator.CreateInstance(type);

Though if you don't know the specific type at compile time, leave off the cast, and just use object, dynamic, or a base class.

To pass args:

Activator.CreateInstance(type, arg1, arg2);
codenheim
  • 20,467
  • 1
  • 59
  • 80