I am using a ranges with a method I’m working with, and my manager has asked me to use Enum instead of integers, so that instead of having this:
public virtual int MyMethod(int value)
{
int result = 0;
if (value >= 0 && value <= 3333)
{
result = 1;
}
else if (value >= 3334 && value <= 6666)
{
result = 2;
}
else if (value >= 6667 && value <= 10000)
{
result = 3;
}
return result;
}
I work with something like this:
public virtual int MyMethod(int value)
{
int result = 0;
if (value >= (int)EnumClass.Range.Low.Min && value <= (int)EnumClass.Range.Low.Max)
{
result = 1;
}
else if (value >= (int)EnumClass.Range.Medium.Min && value <= (int)EnumClass.Range.Medium.Max)
{
result = 2;
}
else if (value >= (int)EnumClass.Range.High.Min && value <= (int)EnumClass.Range.High.Max)
{
result = 3;
}
return result;
}
The EnumClass has other Enum for other methods (i.e. Rating, Priority), so I wished for Range to remain its own variable, kinda like this:
public static enum Rating
{
Low = 1,
Medium,
High
};
public static enum[] Range =
{
enum Low
{
Min = 0,
Max = 3333
},
enum Medium
{
Min = 3334,
Max = 6666
},
enum High
{
Min = 6667,
Max = 10000
}
};
I get an error while initializing that array, however, so is there any other way I could achieve this? If possible, I would like to avoid making them three Enum, but if it’s unavoidable I’ll work with this:
public static enum Rating
{
Low = 1,
Medium,
High
};
public static enum RangeLow
{
Min = 0,
Max = 3333
};
public static enum RangeMedium
{
Min = 3334,
Max = 6666
};
public static enum RangeHigh
{
Min = 6667,
Max = 10000
};
You’re being asked (or worse, told) to use a wrench to pound a nail. It will work, but it is unpleasant and this is not an appropriate use for enums, as has been mentioned.
I would suggest that if this is a common application, having a range defined and checking against it, that you encapsulate the Range in a class (which would probably be just a pair of properties for minimum and maximum, as well as methods for checking values against the range and so forth), and then use that.