views:

110

answers:

2
+1  Q: 

Generics question

I have a generic class

public class Decoder<SIGNAL> where SIGNAL : signalType, new()

signalType is a abstract class. How do I declare a dynamic field to store it? The following code will throw a compile error saying that Decoder must be a non abstract type generic.

public class DecoderParent
{
    private Decoder<signalType> decoder;

    public DecoderParent(keys key)
    {
     switch(key)
    {
        case keys.SignalOne:
            {
                decoder = new Decoder<signalONE>();
                break;
            }
        case keys.signalTwo:
            {
                decoder = new Decoder<signalTWO>();
                }
        }
    }
}
+1  A: 

Generic types are not covariant like reference types - see my answer here. You cannot assign a Decoder<signalONE> to a variable of type Decoder<signalType>

thecoop
+4  A: 

There are 2 problems you're hitting here

  1. The type signalType violates the generic constraint on the SIGNALTYPE generic parameter. Because it is abstract it cannot satisfy the new() constraint
  2. The assignment between Decoder<signalType> and any other type requires covariance support which is not available in C# (only in interfaces starting in v4.0).

What you need to do is define a non-generic base class which defers it's operations to the generic sub classes.

public abstract class Decoder {
  ...
  abstract void SomeOp();
} 

public abstract class Decoder<SIGNALTYPE> where SIGNALTYPE : signalType,new() {
}

Decoder d = new Decoder<SignalOne>();
JaredPar
worked nicely thanks, except I couldn't use generic method definitions.For example:public override List<SIGNALTYPE> GetList();
Will