Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize Type by name string in .net

Tags:

c#

I have an application that reads its setting at startup from App.config. The application may use different presistent storage providers. Currently I have two implemented: Oracle and Dummy (for test purposes).

Now in my Program.cs I read the name of the type of storage to use. It may be either OracleStorage or DemoStorage. These are type names, the implementations of which reside in a separate dll project.

Now, how do I instantiate an object given that I have a type name?

So I could write:

IStorageProvider storage = new typof(myStorageClassNameReadFromAppConfig);
like image 443
Maxim V. Pavlov Avatar asked Oct 16 '25 00:10

Maxim V. Pavlov


1 Answers

You can use Activator.CreateInstance combined with Type.GetType:

IStorageProvider storage = 
        (IStorageProvider) Activator.CreateInstance(
                             Type.GetType(myStorageClassNameReadFromAppConfig)
                           );
like image 112
Reed Copsey Avatar answered Oct 18 '25 16:10

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!