-1

I want to declare an object based on a variable value.

This is the code that I'm trying to run and that doesn't compiles:

if (bcheck == 0)
    IWebDriver driver = new ChromeDriver();
else if (bcheck == 1)
    IWebDriver driver = new FirefoxDriver();
else if (bcheck == 2)
    IWebDriver driver = new InternetExplorerDriver();

If I try to compile the code, I get this error message:

Embedded statement cannot be a declaration or labeled statement

How can I rewrite the code?

The driver object is used in the code below and I have to keep that name in order to don't change program flow.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
DarioN1
  • 2,460
  • 7
  • 32
  • 67
  • 3
    Declare `driver` beforehand (with no value) and assign to it in each conditional. – Ry- Jan 08 '18 at 08:59
  • 1
    I'd use a `Dictionary`, Similar https://stackoverflow.com/a/42505360/2946329 – Salah Akbari Jan 08 '18 at 08:59
  • 1
    Ironically none of the answers explain the actual error being given, which is a lack of curly braces. – Rotem Jan 08 '18 at 09:03
  • 2
    The `if`-statement is a block construct which defines a scope, a scope of a variable determines its visibility to the rest of a program. So if you don't declare the variable before the `if`-statement, you cannot access it outside. The error message itself is misleading because it tells you that you should use `{}` inside the `if` instead of the embedded statement(one liner) if you want to use a declaration. But if you would do that you still wouldn't be able to access the variable outside of the `if` as mentioned above. – Tim Schmelter Jan 08 '18 at 09:06

4 Answers4

3
IWebDriver driver = null;
if (bcheck == 0)
    driver = new ChromeDriver();
else if (bcheck == 1)
    driver = new FirefoxDriver();
else if (bcheck == 2)
    driver = new InternetExplorerDriver();

Declare IWebDriver outside the if condition and assignment inside the if condition.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Yogesh Patel
  • 818
  • 2
  • 12
  • 26
2

You must declare a single variable :

IWebDriver driver = null;
if (bcheck == 0)
   driver = new ChromeDriver();
else if (bcheck == 1)
   driver = new FirefoxDriver();
else if (bcheck == 2)
   driver = new InternetExplorerDriver();
PMerlet
  • 2,568
  • 4
  • 23
  • 39
2

Don't use if / else, a dictionary is much simpler and more extensible.

var dictionary = new Dictionary<int, IWebDriver>
{
    [0] = new ChromeDriver(),
    [1] = new FirefoxDriver(),
    [2] = new InternetExplorerDriver()
};

var driver = dictionary[bcheck];
Aaron
  • 622
  • 7
  • 15
1

You can declare driver before the if-else statement, but only iniitalize it inside the relevant condition:

IWebDriver driver = null;
if (bcheck == 0)
    driver = new ChromeDriver();
else if (bcheck == 1)
    driver = new FirefoxDriver();
else if (bcheck == 2)
    driver = new InternetExplorerDriver();
Mureinik
  • 297,002
  • 52
  • 306
  • 350