Reputation: 5044
I am using Factory patterns, wherein, based on the interface it will create and return the new concreate object.I am using Generic Type and checking it using switch for different concreate objects. Here's my class layout.
public class Factory<T>
{
public T Instance()
{
switch(T)
{
case IUser:
return new Domain.User();
break;
case IProduct:
return new Domain.Product();
break;
}
}
}
However this throwing me an error:
'T' is a type, which is not valid in the given context
and
Cannot implicitly convert type 'Domain.User' to 'T'
and this is how my client code is calling the above Factory class.
private readonly Factory<IUser> factory = new Factory<IUser>();
IUser oUser = factory.Instance();
Upvotes: 1
Views: 313
Reputation: 726509
You cannot use type in a switch
, but you can switch on type name:
switch(typeof(T).Name) {
case nameof(IUser):
return new Domain.User();
break;
case nameof(IProduct):
return new Domain.Product();
break;
}
Note that this is a pretty inflexible solution, because adding new types to the factory requires a recompile of the fine containing the switch
.
A better approach is to make a registry of types accepted by the factory, or use an existing solution for it, such as autofac.
Here is a skeletal implementation of a factory with registration:
class Factory {
private readonly IDictionary<Type,Func<object>> registry = new Dictionary<Type,Func<object>>();
public void Register<T>(Func<T> make) {
registry.Add(typeof(T), () => (object)make());
}
public T Instance<T>() {
return (T)registry[typeof(T)]();
}
}
You would use the factory as follows:
Factory f = new Factory();
f.Register<IUser>(() => new User());
f.Register<IProduct>(() => new Product());
IUser u = f.Instance<IUser>();
Upvotes: 2