Enum in C#
-
I have an enum say enum1. It has four fields f1,f2,f3,f4. I have allowed this to be set with multiple values. The enum1 is shown bellow:
public enum enum1
{
f1=0,
f2=1,
f3=2,
f4=3
}But this allows enum with any combination of values to be set. I want this enum with particular restricted combination (say f1|f2,f2|f3, and f1|f4 only) to be set. How can i accomplish that? Thanks.
-
I have an enum say enum1. It has four fields f1,f2,f3,f4. I have allowed this to be set with multiple values. The enum1 is shown bellow:
public enum enum1
{
f1=0,
f2=1,
f3=2,
f4=3
}But this allows enum with any combination of values to be set. I want this enum with particular restricted combination (say f1|f2,f2|f3, and f1|f4 only) to be set. How can i accomplish that? Thanks.
Hello You could create a property of the enum1 type
public enum enum1{ f1=0, f2=1, f3=2, f4=3}
private enum1 myEnum1;
public enum1 MyEnum1
{
get ( return myEnum1; }
set
{
if (value == f1 || value == f3)
myEnum1 = value;
else
throw new ArgumentException("Invalid assignment");
}
}Otherwise you could create different enums
public enum enum1{ f2=1, f4=3}
public enum enum2{ f1=0, f3=2}for example.
Kind Regards, John Petersen
-
Hello You could create a property of the enum1 type
public enum enum1{ f1=0, f2=1, f3=2, f4=3}
private enum1 myEnum1;
public enum1 MyEnum1
{
get ( return myEnum1; }
set
{
if (value == f1 || value == f3)
myEnum1 = value;
else
throw new ArgumentException("Invalid assignment");
}
}Otherwise you could create different enums
public enum enum1{ f2=1, f4=3}
public enum enum2{ f1=0, f3=2}for example.
Kind Regards, John Petersen
Thank you very much. And from your side i desires for welcome.
-
I have an enum say enum1. It has four fields f1,f2,f3,f4. I have allowed this to be set with multiple values. The enum1 is shown bellow:
public enum enum1
{
f1=0,
f2=1,
f3=2,
f4=3
}But this allows enum with any combination of values to be set. I want this enum with particular restricted combination (say f1|f2,f2|f3, and f1|f4 only) to be set. How can i accomplish that? Thanks.
If you intend the enum to allow for OR'd combinations as you imply, you should decorate the enum with the Flags[^] attribute. This attribute indicates that an enumeration can be treated as a bit field; that is, a set of flags. Bit fields can be combined using a bitwise OR operation, whereas enumerated constants cannot. Bit fields are generally used for lists of elements that might occur in combination, whereas enumeration constants are generally used for lists of mutually exclusive elements. Therefore, bit fields are designed to be combined with a bitwise OR operation to generate unnamed values, whereas enumerated constants are not. Languages vary in their use of bit fields compared to enumeration constants. Your code will compile without the Flags attribute, but it helps the compiler, the runtime and other developers understand how the enum is supposed to be used.