Reputation: 22770
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
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
Reputation: 283911
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)
Upvotes: 4