1

I am trying to attempt something such as

void Main()
{
    Temp<Bar> Test = new Foo<InheritedBar>();
}

abstract class Temp<T> where T : Bar
{

}

class Foo<T> : Temp<T> where T : Bar
{

}

abstract class Bar
{

}

class InheritedBar : Bar
{

}

The cast does not work, with the error Cannot implicity convert type Foo<InheritedBar> to Temp<Bar>.

However, Temp<InheritedBar> Test = new Foo<InheritedBar>(); and Temp<Bar> Test = new Foo<Bar>();

Both work. Why even though InheritedBar inherits from Bar, it can't be cast to it through generics?

I am using the generic type in a wpf Page, which can not be created as a generic so I can't pass T as its type. I only want the functionality at the time of this of Temp, not any of the derived versions functionality. Is there a better way to do this?

Dispersia
  • 1,436
  • 9
  • 23
  • I don't know about C#, but if this was Java this would be a dupe of [this question](http://stackoverflow.com/q/2745265/5743988). – 4castle Jan 04 '17 at 23:39

1 Answers1

3

The concept you are attempting to utilize is covariance (full explanation on MSDN)

The short answer is that you need to use mark your generic parameter with out; but you can only do that on an interface (changing from an abstract class in your case). Also, depending on your method parameters and return values, you may not be able to mark your interface as covariant.

interface Temp<out T> where T : Bar
{

}
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117