blah blah blah is here! blah blah » Close

up0down
link

so honestly, I want to do it this way, but I can't. It says cannot convert 'bool' to 'int'. I'm asking because I do not fully understand what all I can do with a switch statement. I'm getting the drift I'm going to have to use if statements for this situation?

switch (intMinutes)
{
case (intMinutes >= 60 && intMinutes <= 52):
intHours += 1;
break;
case (intMinutes >= 37 && intMinutes <= 51):
dblTenths = .75;
break;
case (intMinutes >= 22 && intMinutes <= 36):
dblTenths = .50;
break;
case (intMinutes >= 7 && intMinutes <= 21):
dblTenths = .25;
break;
case (intMinutes >= 1 && intMinutes <= 6):
dblTenths = 0;
break;
}

stuckne1
1309

I've got all my signs reversed too, but I fixed that.

last answered one year ago

2 answers

link

actually, you could use a switch but it would look something like this:

int opCode =  intMinutes >= 60 && intMinutes <= 52 ? 0 :
intMinutes >= 37 && intMinutes <= 51 ? 1 :
intMinutes >= 22 && intMinutes <= 36 ? 2 :
intMinutes >= 7 && intMinutes <= 21 ? 3 :
intMinutes >= 1 && intMinutes <= 6 ? 4 : -1;

switch ( opCode ) {
case 0: intHours += 1; break;
case 1: dblTenths = .75; break;
case 2: dblTenths = .50; break;
case 3: dblTenths = .25; break;
case 4: dblTenths = 0; break;
}


using a ternary operator to assign an op code for the switch statement. personally I'd find an if statement set logically more appealing.

stuckne1
1309

Oh sweet! I was thinking there had to be a way somehow. I'm going to stick with the if else like you saying, but I'm just glad to know that it is possible.

up1down
link

Assuming you're using C#, no, you're going to have to use an if/else block.

switch statements are hash based (meaning the value of your case statement are constant / literal values, unique in nature), where as what you've proposed is conditional boolean values.

you gain performance with a switch statement by not having to fall through conditions to test what should be executed (this is where C# is different than traditional C/C++ implementations) at a worst case scenario (where your case is the last in the list).

switches would be similar to having a dictionary / delegate combination:

public delegate Foo(int value);

Dictionary<string, Foo> cases = new Dictionary<string, Foo>();
cases.Add("One", delegate(int val) { someValue = val; });
cases.Add("Two", delegate(int val) { someValue = val + 1; });
cases.Add("Three", delegate(int val) { someValue = val + 2; });

string opCode = "One";
cases[opCode](22);


using boolean as an index, you could ever only have two entries.

stuckne1
1309

Alright, thank you.

MadHatter
2309

actually if you wanted to use a switch, you would do it as posted below:

Feedback