Reputation: 3952
I have two enum like below. But I don't know I can define enum like below. I tried. It seems to work. My first question. Can I define an enum like below ?
[Flags]
public enum SState : int
{
ManuelPassive = 2501601,
AutoPassive = 2501602,
ManuelActive = 2501610,
AutoActive = 2501611,
}
public enum SType : int
{
All,
Active = SState .AutoActive | SState .ManuelActive,
Passive = SState .AutoPassive | SState .ManuelPassive,
}
My second question : If I can define this enum, How can I convert a SType
value to SState
list ?
public statis List<SState> ToList(this SType stype)
{
// What should I do here ?
}
Example Calling :
var list = SType.Active.ToList();
I want this list to be like below :
var list = new List<SState>{ SState.AutoActive, SState.ManuelActive };
Upvotes: 1
Views: 414
Reputation: 37232
The first question is fine - it will compile without problems as long as you don't have a circular definition.
Your second question is more interesting - one solution is to use the Type-Safe Enumeration pattern popularised by Java.
This pattern allows you to add new behaviours to your enums (something a language like Swift supports out of the box, but C# and Java sadly don't). In the below example I have given your enum a Value
and a List
property, as requested.
void Main()
{
Console.WriteLine(SType.Active.Value);
Console.WriteLine(SType.Active.List);
}
[Flags]
public enum SState : int
{
ManuelPassive = 2501601,
AutoPassive = 2501602,
ManuelActive = 2501610,
AutoActive = 2501611,
}
public sealed class SType
{
public static readonly SType Active = new SType(new List<SState>() { SState.AutoActive, SState.ManuelActive });
public static readonly SType Passive = new SType(new List<SState>() { SState.AutoPassive, SState.ManuelPassive });
private SType (List<SState> values)
{
this.Value = (int)values.Aggregate((current, next) => current | next);
this.List = values;
}
public int Value { get; private set; }
public List<SState> List { get; private set; }
}
Upvotes: 2