Reputation: 1670
So, I was wondering if it is acceptable practice or bad practice to use both integer and character types within an Enum type. For example, I am currently working with a payment processing vendor system. They can call our soap request and send ids for payment types anywhere from 1 to 25 and also can send characters such as C,M, and O. I wanted to use an enum for clarity in reading the code, but one problem I am having is that I also wanted to sue a switch for this. Is this a bad practice on handling this, also can I handle this safely in a switch or should I just do a if else, and try parse for handling incorrect casting?
Example of Enum values would be the following:
internal enum PaymentTypeEnum
{
/// <summary>
/// Payment Type Id via Phone from ACI. Note: Int32
/// </summary>
PhonePayment_IVR = '9',
/// <summary>
/// Payment Type Id via electronic from ACI. Note: Int32
/// </summary>
eCollectPayment = '5',
/// <summary>
/// Payment Type Id for CANCEL payment. Note: Char
/// </summary>
CancelPayment = 'C',
}
Upvotes: 0
Views: 232
Reputation: 42260
It seems like ludicrous practice to use char members for enumerations, since they are numeric types under the hood.
Want to see how your example compiles?
//Your code...
internal enum PaymentTypeEnum
{
PhonePayment_IVR = '9',
eCollectPayment = '5',
CancelPayment = 'C',
}
// Compiled...
internal enum PaymentTypeEnum
{
PhonePayment_IVR = 57,
eCollectPayment = 53,
CancelPayment = 67
}
You seem to be missing a level of abstraction. Your enum should represent payment types, then if you need characters to represent each enum member, use a dictionary
Dictionary<PaymentTypeEnum, char> types = new Dictionary<PaymentTypeEnum, char>();
types[PaymentTypeEnum.PhonePayment_IVR] = '9';
types[PaymentTypeEnum.eCollectPayment] = '5';
types[PaymentTypeEnum.CancelPayment] = 'C';
public char GetPaymentType(PaymentTypeEnum pt)
{
if(types.ContainsKey(pt))
{
return types[pt];
}
return default(char); // assuming (char)0 is meaningless in this context...otherwise...
throw new InvalidArgumentException(...);
}
Also, don't suffix your enum with Enum...you already know it's an enum!
Upvotes: 1