Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# how to write abstract method that return enum

Tags:

c#

enums

abstract

I have a base class and few classes derived from it.

I want to declare an enum in the base class as abstract and each class that derived from it will have to create its own different enum.

How can I do it?

I tried the following: declare an abstract method in the base class that return enum type and each class that implement it will return its own enum:

public abstract enum RunAtOptions();

But I get compile error

"The modifier abstract is not valid for this item"
like image 814
Yuval Levy Avatar asked Aug 02 '17 08:08

Yuval Levy


2 Answers

You need to return the actual enum not the enum keyword so if you had the enum MyEnumType like this:

public enum MyEnumType
{
    ValueOne = 0,
    ValueTwo = 1
}

public abstract MyEnumType RunAtOptions();

If you wanted to modify this to use generics you could have the method return T and have a constraint to make T a struct:

public abstract T RunAtOptions() where T : struct;

C# doesn't have a generics constraint to support the enum type.

like image 64
Stephen Wilson Avatar answered Oct 27 '22 19:10

Stephen Wilson


You cannot use the enum keyword as an abstract member. Similar question

Alternatively, you can introduce an abstract dictionary property.

public class Base
{
    public abstract Dictionary<string, int> RunAtOptions { get; }
}

The deriving class could set the property in the constructor.

public class Derived : Base
{
    public override Dictionary<string, int> RunAtOptions { get; }

    public Derived()
    {
        RunAtOptions = new Dictionary<string, int>
        {
            ["Option1"] = 1,
            ["Option2"] = 2
        }
    }
}

Unfortunately using this method won't give you elegant compile-time checks. With this dictionary you can compare option values against entries in the dictionary like this:

if (someObject.Options == RunAtOptions["Option1"]) // someObject.Options is of type `int`
{
    // Do something
}
like image 33
Kapol Avatar answered Oct 27 '22 18:10

Kapol