I have some problem around generics and I don't see my mistake.
Given this code:
public interface IMyInterface { }
public class MyImplementation : IMyInterface { }
public interface IMyFactory<T> where T : class, IMyInterface
{
T Create();
}
public class MyFactory<T> : IMyFactory<T> where T : class, IMyInterface
{
public T Create()
{
// Complex logic here to determine what i would like to give back
return new MyImplementation(); // <--- red squigglies - Cannot implicitly convert type 'ConsoleApp18.MyImplementation' to 'T'
}
}
If I use it like this return new MyImplementation() as T;
it works. No more errors are present.
If I use it like this return (T)new MyImplementation();
i get a code suggestion to remove the unnecessary cast. (Yeah that's what I think too, why is it not possible to return the concrete implementation since it is compatible with T?) and also the first error (Cannot implicitly convert...) is still present.
So why do I get this error and what is the correct implementation to return my concrete implementation?