C#: Statements as expressions

if-Statement as expression

Normales if-Statement:

public static decimal GetPriceByStatement(decimal price, int quantity, bool isPremiumMember)
{
    decimal discountAmount = 0;

    if(quantity >= 12)
    {
        discountAmount += .1M;
    }
    if (isPremiumMember)
    {
        discountAmount += .20M;
    }

    return price * (1 - discountAmount);
}

Das if-Statement als expression:

public static decimal GetPriceByExpression(decimal price, int quantity, bool isPremiumMember)
{
    decimal discountAmount = (quantity >= 12 ? .1M : 0) 
                + (isPremiumMember ? .2M : 0);
    return price * (1 - discountAmount);
}

swtich-statements as expression

Normales switch-Statement:

public static decimal GetNumberOfAccessLevelStatement(AccessLevels accessLevels)
{
    decimal accessLevelNumber = 0;
    switch (accessLevels)
    {
        case AccessLevels.Low:
            accessLevelNumber =  100501;
            break;
        case AccessLevels.LowExtendSecurity:
            accessLevelNumber = 100511;
            break;
        case AccessLevels.Middle:
            accessLevelNumber = 100601;
            break;
        case AccessLevels.MiddleExtendSecurity:
            accessLevelNumber = 100611;
            break;
        case AccessLevels.High:
            accessLevelNumber = 100701;
            break;
        case AccessLevels.HighExtendSecurity:
            accessLevelNumber = 100711;
            break;
        default:
            accessLevelNumber = 0;
            break;
    }
    return accessLevelNumber;
}

Das switch-Statement als switch-expression:

public static decimal GetNumberOfAccessLevelExpression(AccessLevels accessLevels)
{
    decimal accessLevelNumber = accessLevels switch
    {
        AccessLevels.Low => 100501,
        AccessLevels.LowExtendSecurity => 100511,
        AccessLevels.Middle => 100601,
        AccessLevels.MiddleExtendSecurity => 100611,
        AccessLevels.High => 100701,
        AccessLevels.HighExtendSecurity => 100711,
        _ => 0,
    };
    return accessLevelNumber;
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert