简体   繁体   中英

Rewrite if statement to switch case with C#

I would like to improve my C# code by using switch case instead of if statement. Actually, I have something like that:

// Refuse case when validator2 click to send : notator mail + validator 1 copy
if (EtapeSuivanteAModifier.Statut.Correspond(StatutWorkflowEnumValues.Refuse))
{
    if (EtapeActuelle.Statut.Correspond(StatutWorkflowEnumValues.AValider2))
    {
        documentContainer.MailTo(mail.AdressesMailDestinataires, mail.AdressesMailDestinatairesCopies);
    }
}
// Agree case when validor 1 click to send : mail validator 2 + notator copy
else if (EtapeSuivanteAModifier.Statut.Correspond(StatutWorkflowEnumValues.AValider2))
{
    documentContainer.MailTo(mail.AdressesMailDestinataires, mail.AdressesMailDestinatairesCopies);
}
else
{
    documentContainer.MailTo(mail.AdressesMailDestinataires);
}

In this case, when the first if statement is succeeded, the else statement is called and I don't want that. So I would like to replace by switch case.

But How I can set a switch condition on .Correspond() method with Enumerables ?

Something like this:

switch (EtapeSuivanteAModifier.Statut.Correspond(...))
{ 
    case ( ?? ):
        break;
    case ( ?? ):
        break;
}

You're doing twice the same thing in both if/else if

if (EtapeSuivanteAModifier.Statut.Correspond(StatutWorkflowEnumValues.Refuse))
{
    if (EtapeActuelle.Statut.Correspond(StatutWorkflowEnumValues.AValider2))
    {
        documentContainer.MailTo(mail.AdressesMailDestinataires, mail.AdressesMailDestinatairesCopies);
    }
}
// Agree case when validor 1 click to send : mail validator 2 + notator copy
else if (EtapeSuivanteAModifier.Statut.Correspond(StatutWorkflowEnumValues.AValider2))
{
    documentContainer.MailTo(mail.AdressesMailDestinataires, mail.AdressesMailDestinatairesCopies);
}

You can refactorize your condition such as:

if ((EtapeSuivanteAModifier.Statut.Correspond(StatutWorkflowEnumValues.Refuse)     // Condition in the if
           && EtapeActuelle.Statut.Correspond(StatutWorkflowEnumValues.AValider2)) // <---^
     || EtapeSuivanteAModifier.Statut.Correspond(StatutWorkflowEnumValues.AValider2)) // Condition in the else if
{
    documentContainer.MailTo(mail.AdressesMailDestinataires, mail.AdressesMailDestinatairesCopies); // Same action
}
else
{
    documentContainer.MailTo(mail.AdressesMailDestinataires);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM