I have the following classes and interfaces:
public interface IThing
{
string Name { get; }
}
public class Thing : IThing
{
public string Name { get
The compiler is stumbling over the conversion from MyThingConsumer
to ThingConsumer
even though T:IThing
and MyThingConsumer:Thingconsumer
and Thing:IThing
. Which is quite a few hoops for it to jump through!
The code works if you use return new MyThingConsumer() as ThingConsumer
instead of a direct cast. You know the result will never be null
, and the compiler is happy because it is guaranteed a return value of the right type at runtime.
Edit: Here is the full code I used for testing (in Snippy):
public interface IThing
{
string Name { get; }
}
public class Thing : IThing
{
public string Name { get; set; }
}
public abstract class ThingConsumer where T : IThing
{
public string Name { get; set; }
}
public class MyThingConsumer : ThingConsumer
{
}
public static class ThingConsumerFactory where T : IThing
{
public static ThingConsumer GetThingConsumer()
{
if (typeof(T) == typeof(Thing))
{
return new MyThingConsumer() as ThingConsumer;
}
else
{
return null;
}
}
}
...
var thing = ThingConsumerFactory.GetThingConsumer();
Console.WriteLine(thing);