C # enum covariance not working

I need to use enum as a 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 tried to use Enum.

 IColoredObject<Enum> coloredObject = car as IColoredObject<Enum>; 

I tried to use IConvertible, which is the Enum interface.

 IColoredObject<IConvertible> coloredObject = car as IColoredObject<IConvertible>; 

But every time it does not work (it was null).

What should i use? Or how can I do this?

(I do not want to use EnumColor in the second part of the code because I need two independent codes connected only to the interface.)

+6
source share
2 answers

Covariance is not supported. "Value Types" Enum falls into this category and therefore does not work.

The difference in common interfaces is supported only for reference types. Value types do not support variance. For example, IEnumerable<int> (IEnumerable (Of Integer) in Visual Basic) cannot be implicitly converted to IEnumerable<object> (IEnumerable (Of Object) in Visual Basic) because integers are represented by a value type.

MSDN source

+8
source

Finally, I solved my problem using the general method. These are a few characters more, but it works.

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

Second code:

 public interface IColoredObject<EnumColorType> { EnumColorType Color { get; } } public static class IndependentClass { public static void DoesItWork<EnumColorType>( object car ) { IColoredObject<EnumColorType> coloredObject = car as IColoredObject<EnumColorType>; if( coloredObject == null ) Console.WriteLine( "It doesn't work." ); else { Console.WriteLine( "It works." ); int colorNumber = (int)( coloredObject.Color as object ); Console.WriteLine( "Car has got color number " + colorNumber + "." ); } } } 
0
source

All Articles