Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# enum covariance doesn't work

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.)

like image 970
user1576055 Avatar asked Jan 18 '14 10:01

user1576055


1 Answers

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 to IEnumerable<object> (IEnumerable(Of Object) in Visual Basic), because integers are represented by a value type.

Source MSDN

like image 75
Sriram Sakthivel Avatar answered Oct 05 '22 12:10

Sriram Sakthivel