griegs
griegs

Reputation: 22770

Instantiate class based on interface string name

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.

Upvotes: 3

Views: 728

Answers (2)

jamesmortensen
jamesmortensen

Reputation: 34078

It seems to me that you may benefit from being even more abstract. Is there some reason you can't have a superinterface called:

interface IAbstractLocation 

Then, create your concrete classes using the appropriate interface, but with those interfaces inheriting from the AbstractLocation type:

interface ICafe : IAbstractLocation

interface IBusiness : IAbstractLocation

You then would have 1 type:

...Location<IAbstractLocation>();

Which should handle any new type that you might add that inherits from the IAbstractLocation interface.

Upvotes: 2

Ben Voigt
Ben Voigt

Reputation: 283911

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

Upvotes: 4

Related Questions