I need to use enum as covariant type. Let's say i have this code:
public enum EnumColor
{
Blue = 0,
Red = 1,
}
public class Car : IColoredObject<EnumColor>
{
private EnumColor m_Color;
public EnumColor Color
{
get
{
return m_Color;
}
set
{
m_Color = value;
}
}
public Car()
{
}
}
class Program
{
static void Main()
{
Car car = new Car();
IndependentClass.DoesItWork( car );
}
}
and this code:
public interface IColoredObject<out EnumColorType>
{
EnumColorType Color
{
get;
}
}
public static class IndependentClass
{
public static void DoesItWork( object car )
{
IColoredObject<object> coloredObject = car as IColoredObject<object>;
if( coloredObject == null )
Console.WriteLine( "It doesn't work." );
else
{
Console.WriteLine( "It works." );
int colorNumber = (int)( coloredObject.Color );
Console.WriteLine( "Car has got color number " + colorNumber + "." );
}
}
}
I was trying to use Enum.
IColoredObject<Enum> coloredObject = car as IColoredObject<Enum>;
I was trying to use IConvertible which is interface of Enum.
IColoredObject<IConvertible> coloredObject = car as IColoredObject<IConvertible>;
But everytime it doesn't work (it was null).
What should i use ? Or how can i do it ?
(I don't want to use EnumColor in second part of code, because i want two independent codes joined only with interface.)
Covariance is not supported with "Value types" Enum
falls under this category and hence doesn't work.
Variance in generic interfaces is supported for reference types only. Value types do not support variance. For example,
IEnumerable<int>
(IEnumerable(Of Integer) in Visual Basic) cannot be implicitly converted toIEnumerable<object>
(IEnumerable(Of Object) in Visual Basic), because integers are represented by a value type.
Source MSDN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With