Generics question
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>();
}
}
}
}
Solution
There are 2 problems you're hitting here
- The type signalType violates the generic constraint on the SIGNALTYPE generic parameter. Because it is abstract it cannot satisfy the new() constraint
- 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>();
OTHER TIPS
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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow