Imagine C# code like this
ISomeInterface someVar = creator.Create(typeof(SomeClass),
typeof(ISomeInterface));
What should happen? Method creator.Create takes two parameters: first is a type of an object to be created, second is a type that method should cast newly created object to and return as that type.
So, like in example code: we want use interface we know class implements so we ask for creation of object and specify that returned type should be that interface we are interested in.
Is is even possible to implement it somehow? Generics, reflection, dynamic method creation based on some complicated generics declaration? something more sophisticated? I’m open for suggestions.
Of course we are not taking into consideration simplest solution that is explicitly casting returned value to ISomeInterface. Method should return created object as interface we asked for.
If you wonder what do I need it for I’m trying to complicate my working code in futile pursuit of some clever way of simplifying my class factory 🙂
EDIT:
Current generic method Create:
public T Create<T>(Type type)
{
return (T)Activator.CreateInstance(type);
}
But this is not what I want which is provide two types and basically create object of first but return as second. It is not a case that I have Create method for different interfaces implemented in my codebase.
Further example of usage:
IFoo f = Create(typeof(Foo), typeof(IFoo));
IBar b = Create(typeof(Bar), typeof(IBar));
So, as you can see method returns different interfaces each time according to type provided in second parameter. And there is no way to use type constrains or I don’t see how to do it.
If you want your
Create()method to returnISomeInterfacewithout having to explicitly cast, then you obviously need to make itCreate<ISomeInterface>().To dynamically construct and instance of passed type you obviously need to use reflection, though
Activatorwould make it easier.