Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate class based on interface string name

Tags:

c#

interface

I have a class that implements an interface like this;

... = new Location<ICafe>();
... = new Location<IBusiness>();
etc

If I want to expand the number of Location types I need to edit code at the moment.

Is there a way I can instantiate the class based on the string name of the interface?

So I would get Cafe or Business from the database and I'd like to instantiate the above using the string names of the interface.

edit

I should note that I use ICafe, IBusiness etc, later on in code to determine what type of item this is and what to display on screen.

like image 464
griegs Avatar asked Sep 03 '26 20:09

griegs


1 Answers

Yes, reflection will let you do this, but there will be several steps:

  • Get a System.Type corresponding to the name, for example ifaceType = Type.GetType(string)

  • Get a System.Type corresponding to the generic type template, starting with any set of parameters, for example genericType = typeof (Location<ICafe>).GetGenericTypeDefinition()

  • Combine the two: specificType = genericType.MakeGenericType(ifaceType)

  • Create an instance: Activator.CreateInstance(specificType)

like image 191
Ben Voigt Avatar answered Sep 05 '26 10:09

Ben Voigt



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!