Generic question

advertisements

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>();
                }
        }
    }
}


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>();