0

is there a way to combine flags within an Enum but to restrict the possible combinations? I have an enum like this:

[Flags]
public enum CopyFlags
{
    /// <summary>
    /// Copy members regardless of their actual case
    /// </summary>
    CaseSensitive = 1,
    /// <summary>
    /// Indicates if a leading underscore (e.g. _myMember) should be ignored while comparing member-names.
    /// </summary>
    IgnoreLeadingUnderscore = 2,
    /// <summary>
    /// Indicates if only properties should be copied. Usefull when all technical data is stored in properties. 
    /// </summary>
    PropertiesOnly = 4
}

Now I want to also introduce a FieldsOnly-value but ensure that it is only used when PropertiesOnly is not present. Is this possible?

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111

2 Answers2

4

No, it is not possible. It's not even possible to restrict the values to being the items listed. For example, the following is allowed in C#:

CopyFlags flags = (CopyFlags)358643;

You need to perform your validation explicitly inside of the methods which include a CopyFlags parameter.

Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
1

No, it's not possible within the context of the enum; instead, you'd have to validate it:

public void DoSomething(CopyFlag flag)
{
   if (flag.HasFlag(CopyFlags.PropertiesOnly) && flag.HasFlag(CopyFlags.FieldsOnly))
      throw new ArgumentException();

}
Brian Mains
  • 50,520
  • 35
  • 148
  • 257
  • Then use `(flag & CopyFlags.PropertiesOnly) == CopyFlags.PropertiesOnly or (flag & CopyFlags.FieldOnly) == CopyFlags.FieldOnly`. That method was a shortcut for that. – Brian Mains Aug 28 '14 at 14:06