Way to use different constructors on same variable based on switch-case outcome

Viewed 72

Consider this code:

switch(formatindex)
{
    case 0:
      var myExporter = new PngExporter { Background = OxyColors.Black };
      fileExtension = ".jpg";
    case 1:
      var myExporter = new SvgExporter();
      fileExtension = ".svg";
}

Of course this won't compile, since I declare myExporter twice. The question is, is there a neat way to choose the type/constructor based on the switch-case outcome.

In my case (which caused this question), the rest of the code using myExporteris the same no matter which type is chosen, because only properties that are used are width and height and these all behave the same way with both types of exporters.

I don't want to write the subsequent code twice, which is why I thought I could do something similar to the shown code.

1 Answers

If the two types inherit from the same base class/interface then:

BaseTypeClass myExporter;
switch(formatindex)
{
    case 0:
      myExporter = new PngExporter { Background = OxyColors.Black };
      fileExtension = ".jpg";
    case 1:
      myExporter = new SvgExporter();
      fileExtension = ".svg";
}

If you can't add a common ancestor for the two then consider creating wrappers that do have.


In any case if these are the only two cases you have consider using an if-else:

BaseTypeClass myExporter;
if (formatindex == 0)
{
      myExporter = new PngExporter { Background = OxyColors.Black };
      fileExtension = ".jpg";
}
else
{
      myExporter = new SvgExporter();
      fileExtension = ".svg";
}

In general, this kind of function matches the design pattern of Factory so I'd recommend reading into it.

Related