DISABLE ADBLOCK

ADBlock is blocking some content on the site

ADBlock errore

Enum property in parent class should change inside derive class

StackOverflow https://stackoverflow.com/questions/18165270
  •   c#  -  .net
  •  | 
  •  
  •  | 
  •   ( words)
 Checked

Question

If I have in my Parent class property ConditionStatus of datatype ConditionEnum like

interface IArticle
{
    ConditionEnum ConditionStatus {get; set;}
}

enum is represent like ConditionEnum {New, Used};

I'm wonder how can I change this ConditionEnum in child class so that ArticleA which implements IArticle can have enum like ConditionEnum {Red, Blue, Yellow}; and ArticleB which also implements IArticle have enum like ConditionEnum {Point, Comma, Slash}; I think you've got an idea.

How would you do it?

Solution

You could make your interface generic:

public interface IArticle<T> where T : struct
{
    T ConditionStatus { get; set; }
}

public class ArticleA : IArticle<ColorEnum>
{
    public ColorEnum ConditionStatus { get; set; }
}

public class ArticleB : IArticle<PunctuationEnum>
{
    public PunctuationEnum ConditionStatus { get; set; }
}

Note that you can't enforce that T is an enum... and you do need to specify which enum your implementation will use. It's not entirely clear whether that's going to help you or not, but it's about all there is...

OTHER TIPS

Since enums can't derive from other enum types or interfaces, it's almost impossible. What you describe seems polymorphism to me. But AMAIK, you can't apply polymorphism to enums.

  1. That's not a parent class, but an interface.
  2. You can have an enum inside a class, you'd refer to it as ClassA.ConditionEnum.*:

.

class MyClass : IArticle {
    public enum ConditionEnum { Red, Blue, Yellow };

    public ConditionEnum myenum;
}

MyClass c = new MyClass();
c.myenum = MyClass.ConditionEnum.Red;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow