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"
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.
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
}
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