c# . getting unreachable code error in switch statement - c#

im getting unreachable code detected error in below code.
could anybudy pls guide on this issue , wil get bundle of thanks from bottom of my heart
public decimal SetDiscountLevel()
{
int range= spentAmount/500;
switch(range)
{
case 0:
return 0;
break;
case 1:
return 0.05m;
break;
case 2:
return 0.06m;
break;
case 3:
return 0.08m;
break;
default:
return 0.1m;
break;
}
}

Remove break; after return; keyword because if you use return; in case then break; will not be reached because you just stopped execution of loop with return; keyword.
See code below
public decimal SetDiscountLevel()
{
int range= spentAmount/500;
switch(range)
{
case 0:
return 0;
case 1:
return 0.05m;
case 2:
return 0.06m;
case 3:
return 0.08m;
default:
return 0.1m;
}
}

In each case you are immediately returning a value, meaning that the following break will never be executed.
Just do the following
public decimal SetDiscountLevel()
{
int range= spentAmount/500;
switch(range)
{
case 0:
return 0;
case 1:
return 0.05m;
case 2:
return 0.06m;
case 3:
return 0.08m;
default:
return 0.1m;
}
}

Related

C# Switch statement scenario

UPDATED:
Is there a way to accomplish what the code below attempts to do (doesn't pass syntax because case 2 and case 3 can't have duplicate declarations and/or because num can't be 2 and 3 at the same time)?
var num = 0;
switch (num)
{
case 1:
//do stuff applicable to 1 only;
break;
case 2:
//do stuff applicable to 2 only;
break;
case 3:
//do stuff applicable to 3 only;
break;
case 2:
case 3:
//do stuff applicable to 2 and 3 only;
break;
}
The question is confusingly posed. I think what you want is to have a case that runs for two, a case that runs for three, and a case that runs for two-or-three.
Just use two switches:
switch (num)
{
case 1: One(); break;
case 2: Two(); break;
case 3: Three(); break;
}
switch (num)
{
case 2:
case 3: TwoOrThree(); break;
}
Or
switch (num)
{
case 1: One(); break;
case 2:
case 3:
switch (num)
{
case 2: Two(); break;
case 3: Three(); break;
}
TwoOrThree();
break;
}
Or duplicate the code:
switch (num)
{
case 1: One(); break;
case 2: Two(); TwoOrThree(); break;
case 3: Three(); TwoOrThree(); break;
}
I would NOT recommend un-duplicating the code like this:
switch (num)
{
case 1: One(); break;
case 2: Two(); goto twoOrThree; break;
case 3: Three(); twoOrThree: TwoOrThree(); break;
}
Yuck.
not with a single-level switch (or a nasty GOTO). A switch can only execute one case. A better solution would be a nested if (or switch) within the 2/3 case:
switch (num)
{
case 1:
//do stuff applicable to 1 only
break;
case 2:
case 3:
if(num == 2)
{
//do stuff applicable to 2 only
}
if(num == 3)
{
//do stuff applicable to 3 only
}
//do stuff applicable to 2 OR 3
break;
}
It's as simple as this...
switch (value)
{
case 1:
// Do 1 stuff
break;
case 2:
case 3:
// We can use an if-else construct here given that there's only two possibilities.
if (value == 2)
{
// 2 only stuff here
}
else
{
// 3 only stuff here
}
// Do anything applicable to BOTH here, or above the if construct, depending on your requirements.
break;
default:
// Any other stuff here
break;
}
Or just use an if construct, which is arguably cleaner (switch is really only intended for simple many to one logical mappings)...
if (value == 1)
{
// 1 stuff
}
else if (value == 2 || value == 3)
{
if (value == 2) {
// 2 stuff only
}
else
{
// 3 stuff only
}
// 2 or 3 stuff, or above the if construct above, if you require.
}
else
{
// Anything else here
}
Or simply...
switch (value)
{
case 1:
OneStuff();
break;
case 2:
TwoStuff();
TwoOrThreeStuff();
break;
case 3:
ThreeStuff();
TwoOrThreeStuff();
break;
default:
AnythingElse();
}
And wrap what you need to do for each of the above in separate methods.
The third method would be my preference here. It's cleaner and easier to debug than using complex mixtures of switch and if.
You could just use if statements instead
var num = 0;
if(num == 1)
{
// do stuff applicable to 1 only
}
else if(num == 2)
{
// do stuff applicable to 2 only
}
else if(num == 3)
{
// do stuff applicable to 3 only
}
if(num == 2 || num == 3)
{
// do stuff applicable to 2 AND 3
}
Or as a switch and an if
switch (num)
{
case 1:
// do stuff applicable to 1 only
break;
case 2:
// do stuff applicable to 2 only
break;
case 3:
// do stuff applicable to 3 only
break;
}
if(num == 2 || num == 3)
{
// do stuff applicable to 2 AND 3
}
You could use the goto case statement and have a unique identifier for combined operations in case 2 and 3. Make sure that that is never hit by any other number:
var num = 0;
var text = "";
switch (num)
{
case 1:
text = "do stuff applicable to 1 only";
break;
case 2:
text = "do stuff applicable to 2 only";
goto case 23;
case 3:
text = "do stuff applicable to 3 only";
goto case 23;
case 23:
text = "do stuff applicable to 2 AND 3";
break;
}
The use of goto is not recommended in general but it is common to use it in switch-statements and situations like that.

Switch statement object to int problems

I am trying to use the selectedItem command to see what has been selected in the list box and then use the switch to set the activityLevel variable depending on what has been selected. I then need to be able to multiply that variable by the BMR variable that is set as a double. Then the result is displayed in a label.
string activityLevel = lstActivityLevel.SelectedItem.ToString();
switch (activityLevel)
{
case 1:
activityLevel = Convert.ToInt32(ACTIVTY_LEVEL2);
break;
case 2:
activityLevel = Convert.ToInt32(ACTIVTY_LEVEL3);
break;
case 3:
activityLevel = Convert.ToInt32(ACTIVTY_LEVEL4);
break;
case 4:
activityLevel = Convert.ToInt32(ACTIVTY_LEVEL5);
break;
}
//Display BMR in label
lblBMRResult.Text = (BMR*activityLevel).ToString();
You can use SelectedIndex, then each item of lstActivityLevel set to number from 0 to 4:
double activityLevel = 0;
switch (lstActivityLevel.SelectedIndex)
{
case 0:
activityLevel = ACTIVTY_LEVEL1;
break;
case 1:
activityLevel = ACTIVTY_LEVEL2;
break;
case 2:
activityLevel = ACTIVTY_LEVEL3;
break;
case 3:
activityLevel = ACTIVTY_LEVEL4;
break;
case 4:
activityLevel = ACTIVTY_LEVEL5;
break;
}
lblBMRResult.Text = (BMR * activityLevel).ToString();
You convert SelectedItem value to string. And value 1 (int) is not the same as "1" (string)... So, you have to change your switch statement to:
switch (activityLevel)
{
case "1":
blah, blah...
break;
}
and so on..
Or do not call ToString() on SelectedItem.
Or you can use SelectedIndex instead of SelectedItem..

Turn if in to switch statement

could I turn this into a switch statement ?
if (donation_euro.Text.Trim().Equals(""))
{
donation_euro.Text = "00.00";
}
if (donation_lui.Text.Trim().Equals(""))
{
donation_lui.Text = "00.00";
}
if (donation.Text.Trim().Equals(""))
{
donation.Text = "00.00";
}
No, because your are not switching on a single variable, but multiple.
I suspect your motivation to do this, is to make the code more readable ? If this is the case, you could put the common logic of your three if's into a method, to reuse the code and better convey the intent.
Not Possible.as switch takes Expression and executes the matching Constant Case Label.
From MSDN :Switch-Case
Each case label specifies a constant value. The switch statement
transfers control to
the switch section whose case label matches
the value of the switch expression
Switch(Expression)
{
case constant1://statements
break;
case constant2://statements
break;
case constant3://statements
break;
}
if you want to switch with single value then it is possible
int a = 3;
if (a == 1)
{
//statements
}
else if(a == 2)
{
//statements
}
else if(a == 3)
{
//statements
}
else if(a == 4)
{
//statements
}
else
{
//statements
}
can be converted into switch as below:
int a = 3;
switch(a)
{
case 1: //statements
break;
case 2: //statements
break;
case 3: //statements
break;
case 4: //statements
break;
default : //statements
break;
}

c# Switch issue. Homework

This is what I have so far. My problem is that none of the cases are responding when you enter either the correct or incorrect answer. I'm not really sure where to go from here. The program asks you answer two random numbers being multiplied. And then it should give you one of the eight responses.
int result = 0;
int caseSwitch = 0;
string question = DoMultiplication(out result);
Console.WriteLine(question);
int answer = Convert.ToInt32(Console.ReadLine());
if (answer == result)
{
switch (caseSwitch)
{
case 1:
Console.WriteLine("Very Good");
break;
case 2:
Console.WriteLine("Excellent");
break;
case 3:
Console.WriteLine("Nice Work");
break;
case 4:
Console.WriteLine("Keep up the good work!");
break;
}
}
else
{
switch (caseSwitch)
{
case 1:
Console.WriteLine("No, Please Try Again.");
break;
case 2:
Console.WriteLine("Wrong, Try Once More");
break;
case 3:
Console.WriteLine("Don't Give Up!");
break;
case 4:
Console.WriteLine("No, Keep Trying!");
break;
caseSwitch is always 0, so your switch will always fall through without writing anything to console.
If you want a random response you could do something like this:
int result = 0;
int caseSwitch = new Random().Next(1, 4);
string question = DoMultiplication(out result);
Console.WriteLine(question);
int answer = Convert.ToInt32(Console.ReadLine());
if (answer == result)
{
switch (caseSwitch)
{
case 1:
Console.WriteLine("Very Good");
break;
case 2:
Console.WriteLine("Excellent");
break;
case 3:
Console.WriteLine("Nice Work");
break;
case 4:
Console.WriteLine("Keep up the good work!");
break;
}
}
else
{
switch (caseSwitch)
{
case 1:
Console.WriteLine("No, Please Try Again.");
break;
case 2:
Console.WriteLine("Wrong, Try Once More");
break;
case 3:
Console.WriteLine("Don't Give Up!");
break;
case 4:
Console.WriteLine("No, Keep Trying!");
break;
CaseSwitch is always = 0.
You need to assign a value to it, and-or add a default case to your switch.
You have your int caseSwitch = 0; and I don't see you changing it in your code to any of 1-4. So what do you expect it to do if you dont have the caseSwitch changed...

Add a additional condition to Case Statement in Switch

Is it possible to add a additional Condition to Switch Statement like below in C#
switch(MyEnum)
{
case 1:
case 2:
case 3 && Year > 2012://Additional Condtion Here
//Do Something here..........
break;
case 4:
case 5:
//Do Something here..........
break;
}
In above mentioned example if MyEnum = 3 then it has to be excuted if Year > 2012... Is it possible?
[EDITED]
Year > 2012 is not applicable to case 1 & case 2.
C#7 new feature:
case...when
https://learn.microsoft.com/en-us/dotnet/articles/csharp/whats-new/csharp-7
public static int DiceSum4(IEnumerable<object> values)
{
var sum = 0;
foreach (var item in values)
{
switch (item)
{
case 0:
break;
case int val:
sum += val;
break;
case IEnumerable<object> subList when subList.Any():
sum += DiceSum4(subList);
break;
case IEnumerable<object> subList:
break;
case null:
break;
default:
throw new InvalidOperationException("unknown item type");
}
}
return sum;
}
In order for it to work the way you've indicated with the fallthrough logic for 1 and 2, I'd suggest moving the //do something here portion out to a method or function and then doing this:
case 1:
case 2:
DoSomething();
break;
case 3:
if(Year > 2012) { DoSomething(); }
break;
The other alternative would be:
case 1:
case 2:
case 3:
if (MyEnum != 3 || Year > 2012) {
// Do something here
}
break;
but I think the first option is much more intuitive and readable.
The answer is no.
You'll need the following:
switch (MyEnum)
{
case 1:
case 2:
DoSomething();
break;
case 3:
if (Year > 2012) DoSomething();
break;
}
You can't add condition to a case. Case clause has to be a compile time constant. Instead you can use an if statement inside the case statement.
case 3:
if( > 2012)
{
//Do Something here..........
}
break;
You have to use the if condition inside your case , you can't use && in case statement, use like below:
switch(MyEnum)
{
case 1:
case 2:
case 3: //Additional Condtion Here
if (Year > 2012)
{
//Do Something here..........
}
break;
case 4:
case 5:
//Do Something here..........
break;
}
Or, alternatively, you can add the condition to the switch:
switch (MyEnum!=3 || Year>2012 ? MyEnum : -1)
{
case 1:
case 2:
case 3:
//Do Something here..........
break;
case 4:
case 5:
//Do Something here..........
break;
}
Most of the time, I do something like that...
(sorry for the naming, the use case didn't inspire me)
Considering those private classes:
private class NumberState
{
public static NumberState GetState(int number, int year)
{
if (number == 1)
return new FirstNumberState();
if (number == 2)
return new FirstNumberState();
if (number == 3 && year > 2012)
return new FirstNumberState();
if (number == 4)
return new SecondNumberState();
if (number == 5)
return new SecondNumberState();
return new DefaultNumberState();
}
}
private class FirstNumberState : NumberState { }
private class SecondNumberState : NumberState { }
private class DefaultNumberState : NumberState { }
Then you can do:
switch (NumberState.GetState(MyEnum, Year))
{
case FirstNumberState _:
// do something
break;
case SecondNumberState _:
// do something
break;
case DefaultNumberState _:
default:
throw new Exception("Unhandled number state");
}
It's easy to read even when your conditions get more complicated.
You can use C# 8 feature
public static bool SomeHelper(int value)
=> value switch
{
100 => true,
var x when x >= 200 && x <= 300 => true,
_ => false, // All other values
};
You will have true with values 100, 200...300 and false with other values
Also you can use params:
public static bool SomeHelper(int value, bool param)
=> value switch
{
100 => true,
var x when x >= 200 && x <= 300 && param => true,
_ => false, // All other values
};
in this case you will have true only if value is 100 and param is false

Categories

Resources