-2

I'm getting a compile error when I try to compile this

The type 'WpfApplication2.CommandInstrumentTrade' cannot be used as type parameter 'T' in the generic type or method 'WpfApplication2.GenericWindowBase'. There is no implicit reference conversion from 'WpfApplication2.CommandInstrumentTrade' to 'WpfApplication2.GenericCommandBase'

public interface IBaseClass
{
    int ID { get; set; }
}

public class BaseClass : IBaseClass
{
    public int ID { get; set; }
}

public class DerivedClass : BaseClass
{
}

public class Command
{
}

public class GenericCommandBase<T> : Command where T : IBaseClass
{
}

public class DerivedGenericCommand : GenericCommandBase<DerivedClass>
{
}

public class GenericWindowBase<T> where T : GenericCommandBase<IBaseClass>
{
}

public class DerivedGenericWindow : GenericWindowBase<DerivedGenericCommand> // this line fails
{

}
Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
Ivan Milosavljevic
  • 839
  • 1
  • 7
  • 19
  • The error doesn't match your sample code. The error says you are using `GenericWindowBase `, which fails because `CommandInstrumentTrade` does not satisfy the where condition of `GenericWindowBase`. – Peter Feb 14 '14 at 08:29
  • 2
    Inheritance doesn't compose with generics. Just because `Base` and `Derived` have an inheritance relationship doesn't mean that `Generic` and `Generic` do. – Damien_The_Unbeliever Feb 14 '14 at 08:33
  • @Damien_The_Unbeliever you are right but is there workaround for this? – Ivan Milosavljevic Feb 14 '14 at 08:34
  • Not sure. Might be easier if the question's code wasn't so abstract. I've got *no* idea what concrete problem you're trying to solve, and how you thought that this (attempted) structure would solve it for you. – Damien_The_Unbeliever Feb 14 '14 at 08:35
  • 2
    Search for covariance/contravariance, there are plenty of questions like these on stack overflow. – dcastro Feb 14 '14 at 08:40

1 Answers1

1

The issue is that Generic<Derived> does not satisfy the condition where T : Generic<Base>. Even if Derived derives from Base, Generic<Derived> does not derive from Generic<Base>

There are many questions like that in StackOverflow. Try reading those:

  1. C# Generics Inheritance
  2. generic inheritance in C#?

Inheritance doesn't compose with generics. You need to create some kind of converter from one to another. Maybe if you present some less abstract code we could help You

Community
  • 1
  • 1
Koscik
  • 190
  • 1
  • 3
  • 14