简体   繁体   中英

Best way for a switch statement for multiple if-else

I am trying to convert the lot of 'if else' to switch stements Need pointer for a optimal switch cases, some code structure as below.

Code:

    Public void ImageTest(String format, string path)
    {
        //Other Code

        //if-Else part
        try
        {
            if (strImageFormat.Equals("BMP"))
             {
                   if (Convert.ToString(dataRow["IsEmployee"]).ToUpper() == "TRUE")
                   {
                      ImagePath = string.Format("{0}{1}", fileNameUpper, ".BMP");
                   }
                   else
                    {
                      ImagePath = string.Format("{0}{1}", fileNamelabel, ".BMP");
                    }

             }      
            else if (strImageFormat.Equals("GIF"))
              {
                if (Convert.ToString(dataRow["IsEmployee"]).ToUpper() == "TRUE")
                   {
                    ImagePath = string.Format("{0}{1}", fileNameUpper, ".GIF");
                    }
                    else
                    {
                    ImagePath = string.Format("{0}{1}", fileNameUpper, ".GIF");
                    }
               }
            else if (strImageFormat.Equals("JPEG"))
              {
                if (Convert.ToString(dataRow["IsEmployee"]).ToUpper() == "TRUE")
                  {
                    ImagePath = string.Format("{0}{1}", fileNameUpper, ".JPEG");
                  }
                    else
                    {
                    ImagePath = string.Format("{0}{1}", fileNameUpper, ".JPEG");
                    }
                }
            else if (strImageFormat.Equals("PDF"))
                {
                  if (Convert.ToString(dataRow["IsEmployee"]).ToUpper() == "TRUE")
                    {
                     ImagePath = string.Format("{0}{1}", fileNameUpper, ".PDF");
                    }
                    else
                     {
                      ImagePath = string.Format("{0}{1}", fileNameUpper, ".PDF");
                      }
                 }
        }
        catch(Exception ex)
        {

        }
}

It looks that the code

   if (Convert.ToString(dataRow["IsEmployee"]).ToUpper() == "TRUE")
   {
     ImagePath = string.Format("{0}{1}", fileNameUpper, ".GIF");
   }
   else
   {
     // fileNamelabel expected, not fileNameUpper
     ImagePath = string.Format("{0}{1}", fileNameUpper, ".GIF");
   }

is either redundant or just copy-pasted . Providing that it's copy-pasted:

  if (Convert.ToString(dataRow["IsEmployee"]).Equals("TRUE", StringComparison.OrdinalIgnoreCase))
    ImagePath = string.Format("{0}.{1}", fileNameUpper, strImageFormat);
  else
    ImagePath = string.Format("{0}.{1}", fileNamelabel, strImageFormat);  

Note dot in the changed format: {0}.{1} .

I would rather not use too many switch statements and store the value in a bool then use conditional operator inside a case:

bool _condition = Convert.ToString(dataRow["IsEmployee"]);

switch(strImageFormat)
{
case "JPG":
            ImagePath = _condition  ? string.Format("{0}{1}", fileNameUpper, ".JPEG") : ImagePath = string.Format("{0}{1}", fileNamelabel, ".JPEG") ;
            break;
case "GIF":
            ImagePath = _condition  ? string.Format("{0}{1}", fileNameUpper, ".GIF") : ImagePath = string.Format("{0}{1}", fileNamelabel, ".GIF") ;
            break;
.
.
.
.
.
.
default:
       // DO SOMETHING
}

I'd use a factory pattern for that in C#. That makes your code much more flexible, and since switches of strings are converted to a dictionary in C# anyways, it doesn't matter much in terms of performance.

For details on implementation, I've posted an implementation not so long ago on Naming convention for GoF Factory? .

Just another idea without need of switch statement.

bool isEmployee = Convert.ToString(dataRow["IsEmployee"]).ToUpper() == "TRUE";
ImagePath = string.Format("{0}.{1}", isEmployee ? fileNameUpper : fileNamelabel, strImageFormat);

I think that you shouldn't use a switch case instead of ifs.

you should solve it the right way which means to use polymorphism.

have a look at the design pattern http://www.dofactory.com/net/factory-method-design-pattern

have a look on the following initial skeleton:

public static class TestEliminateSwitch
{
    public static string GetImagePath()
    {
        var formatFactory = new FormatFactory();
        var instance = formatFactory.GetFomatClass("PDF");
        return instance.GetImagePath("TRUE");
    }
}
public class FormatFactory
{
    public FormatBase GetFomatClass(string formatName)
    {
        string className = typeof (FormatBase).FullName.Replace("Base", formatName);
        return Assembly.GetExecutingAssembly()
            .CreateInstance(className) as FormatBase;
    }
}
public abstract class FormatBase
{
    public string fileNameUpper = string.Empty;
    public string fileNamelabel = string.Empty;
    public virtual string GetImagePath(string IsEmployee)
    {
        return string.Format("{0}{1}", IsEmployee.ToUpper() == "TRUE" ? fileNameUpper : fileNamelabel, GetFileExtention());
    }

    public abstract string GetFileExtention();
}
class FormatPDF : FormatBase
{
    public override string GetFileExtention()
    {
        return ".PDF";
    }
}
class FormatGIF : FormatBase
{
    public override string GetFileExtention()
    {
        return ".GIF";
    }
}

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