Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't cast 2nd Enum value to int?

Tags:

c#

I don't get this. I was able to cast my first enum value to int but not the second?

public enum PayPalTransactionType
{
    Authorization = 0, // Debit
    Capture = 1, // Credit
    Refund = 2,
    Void = 3
}

public string GetPayPalTransCode(PayPalServiceBase.PayPalTransactionType payPalTransactionType)
{
    string actionCode = string.Empty;

    switch (payPalTransactionType)
    {
        case (int)PayPalServiceBase.PayPalTransactionType.Authorization:
            actionCode = "Debit";
            break;
        case (int)PayPalServiceBase.PayPalTransactionType.Capture:
            actionCode = "Credit";
            break;
    }

    return actionCode;
}

on my 2nd case statement I get this casting error:

Cannot implicitly convert type int to PayPalTransactionType. An explicit conversion exists (are you missing a cast?)

like image 749
PositiveGuy Avatar asked Nov 29 '22 11:11

PositiveGuy


1 Answers

Why are you trying to cast in the first place? Just leave it as the enum value everywhere:

public string GetPayPalTransCode
    (PayPalServiceBase.PayPalTransactionType payPalTransactionType)
{
    string actionCode = string.Empty;

    switch (payPalTransactionType)
    {
        case PayPalServiceBase.PayPalTransactionType.Authorization:
            actionCode = "Debit";
            break;
        case PayPalServiceBase.PayPalTransactionType.Capture:
            actionCode = "Credit";
            break;
    }

    return actionCode;
}

Additionally, I'd have an explicit default action for unrecognised codes, and just return directly:

public string GetPayPalTransCode
    (PayPalServiceBase.PayPalTransactionType payPalTransactionType)
{
    switch (payPalTransactionType)
    {
        case PayPalServiceBase.PayPalTransactionType.Authorization:
            return "Debit";
        case PayPalServiceBase.PayPalTransactionType.Capture:
            return "Credit";
        default:
            return ""; // Or throw an exception if this represents an error
    }
}

Alternatively, you could use a Dictionary<PayPalTransactionType, string>.

like image 183
Jon Skeet Avatar answered Dec 07 '22 22:12

Jon Skeet