CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

# Thread: How to make these IF statements into a switch

1. Junior Member
Join Date
Jun 2014
Posts
4

## How to make these IF statements into a switch

Hello,

I am a new programmer and while I have the summer off of school I decided to try and teach myself c#. I have done an into to programming course that used visual basics so I have some very basic programming skills.

Ok onto what I am trying to figure out. In the book I am following it wants me to make a program to calculate the costs of having a party through an event coordinator. The book is digital and I forgot my flashdrive at home, I am on vacation, so I only got like 2 pages describing the assignment.

The assignment itself is really easy so I am guessing it's the assignment to introduce us to switch/case statements.

I looked them up but couldn't figure out how to change my long list of IF statements into a switch.

Here are my switch statements.

Code:
private void button1_Click(object sender, EventArgs e)
{
totalGuests = (int)numericUpDown1.Value;
healthy = cbHealthyOption.Checked;
fancy = cbFancyOption.Checked;

if (healthy&&fancy)
{
totalCost = (totalGuests * 25) + (totalGuests * 5 - ((totalGuests * 5) * .05)) + (totalGuests * 15) + 50;
lblTotal.Text = "\$" + totalCost.ToString("#0.00");
}

if (healthy && !fancy)
{
totalCost = (totalGuests * 25) + (totalGuests * 5 - ((totalGuests * 5) * .05)) + (totalGuests * 7.50) + 30;
lblTotal.Text = "\$" + totalCost.ToString("#0.00");
}

if (!healthy && fancy)
{
totalCost = (totalGuests * 25) + (totalGuests * 20) + (totalGuests * 15) + 50;
lblTotal.Text = "\$" + totalCost.ToString("#0.00");
}

if (!healthy && !fancy)
{
totalCost = (totalGuests * 25) + (totalGuests * 20) + (totalGuests * 7.50) + 30;
lblTotal.Text = "\$" + totalCost.ToString("#0.00");
}

if (numericUpDown1.Value == 0)
{
lblTotal.Text = "\$0";
}

}
And here is the full code incase you need to see it all.

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Party_Cost_Estimator
{
public partial class Form1 : Form
{
int totalGuests;
bool healthy;
bool fancy;
double totalCost;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
totalGuests = (int)numericUpDown1.Value;
healthy = cbHealthyOption.Checked;
fancy = cbFancyOption.Checked;

if (healthy&&fancy)
{
totalCost = (totalGuests * 25) + (totalGuests * 5 - ((totalGuests * 5) * .05)) + (totalGuests * 15) + 50;
lblTotal.Text = "\$" + totalCost.ToString("#0.00");
}

if (healthy && !fancy)
{
totalCost = (totalGuests * 25) + (totalGuests * 5 - ((totalGuests * 5) * .05)) + (totalGuests * 7.50) + 30;
lblTotal.Text = "\$" + totalCost.ToString("#0.00");
}

if (!healthy && fancy)
{
totalCost = (totalGuests * 25) + (totalGuests * 20) + (totalGuests * 15) + 50;
lblTotal.Text = "\$" + totalCost.ToString("#0.00");
}

if (!healthy && !fancy)
{
totalCost = (totalGuests * 25) + (totalGuests * 20) + (totalGuests * 7.50) + 30;
lblTotal.Text = "\$" + totalCost.ToString("#0.00");
}

if (numericUpDown1.Value == 0)
{
lblTotal.Text = "\$0";
}

}
}
}

Thanks!

2. Member
Join Date
Apr 2014
Location
in northeast ohio
Posts
94

## Re: How to make these IF statements into a switch

i really do not like this example
if this is from a learn c# book for beginners id be a little disappointed
this nearly amounts to a trick question

1) there are many ways to deal with this but switch case here is no better then using if else in this particular illustration
2) if you had to do it , there are two results calculated in the case this is not a good thing to teach its... anti-pattern
3) by the phrasing of the question
it is insisting that you create a formula to handle many input and output values and situations in a linear manner
in just one method which is not a beginner idea or a good idea in general really for
a illustration to show reason why to use switch case instead of if else
even a callback method can call other methods to do calculations
4) in the same method it use's a bunch of bad design principals ,
hard coded variables all over abbreviated names ect...

that said...

the first answer is one way to look at it,
i think its ugly and even then its not a direct answer to the question.

the second answer is even uglier however
it is exactly how you would convert the entire 2 booleans and if statement in one shot
into a linear numeric switch that covered all cases, i used enum's for each case, it is ugly ,
you would not normally ever do this,
it probably would never be done, unless you have done it for a reason before. and certainly not on something so simple.
typically if you have a lot of booleans that need to be all converted for linear switching you instead make a custom class
which is beyond the scope of this post

Code:
// possibly the worst test example for a book to choose for a beginner tutorial
// to illustrate using switch case instead of if else i ever saw

public static void SwitchCaseTestExampleA()
{
// like this
switch (healthy)
{
case true:
switch (fancy)
{
case true:
// healthy and fancy

break;
default:
// healthy but not fancy

break;
}
break;
default:
switch (fancy)
{
case true:
// unhealthy and fancy

break;
default:
// neither healthy or fancy

break;
}
break;
}
// this would go at the bottom or the formula would need to get altered
//if (numericUpDown1.Value == 0)
//{
//    lblTotal.Text = "\$0";
//}
}

// this is as shown below in reality what you would have to do basically
// to turn the entire method into one linear switch case
// i just used the words nocost for that if(lbltotal == 0) statement to remove and add it to the cases

enum foodtypes
{
nocostneitherhealthyorfancy = 0,
nocosthealthybutnotfancy = 1,
nocostfancybutnothealthy = 2,
nocosthealthyandfancy = 3,
neitherhealthyorfancy = 4,
healthybutnotfancy = 5,
fancybutnothealthy = 6,
healthyandfancy = 7
};
public void SwitchCaseTestExampleB()
{
// or like this
// these abbreviations are only temporary in scope to set the integer variable val
//
int val = 0, f = 0, h = 0, n =0;
if (healthy) h = 1;
if (fancy) f = 2;
if (numericUpDown1.Value != 0) n = 4;
val = h + f + n;

// typically val is set from the enum the user picks a food that food obj has a foodtype

switch (val)
{
case (int)foodtypes.nocostneitherhealthyorfancy:

break;
case (int)foodtypes.nocosthealthybutnotfancy:

break;
case (int)foodtypes.nocostfancybutnothealthy:

break;
case (int)foodtypes.nocosthealthyandfancy:

break;
case (int)foodtypes.neitherhealthyorfancy:

break;
case (int)foodtypes.healthybutnotfancy:

break;
case (int)foodtypes.fancybutnothealthy:

break;
case (int)foodtypes.healthyandfancy:

break;
// in the case were the value retrieved is completely unexpected
default:
break;
}
}
Last edited by willmotil; June 22nd, 2014 at 02:37 AM.

3. ## Re: How to make these IF statements into a switch

ps: Do NOT turn that in...

4. Member
Join Date
Apr 2014
Location
in northeast ohio
Posts
94

## Re: How to make these IF statements into a switch

I decided to try and teach myself c#
In the book I am following it wants me to make a program to calculate
the costs of having a party through an event
I am guessing it's the assignment to introduce us to switch/case statements
how to change my long list of IF statements into a switch
this is not homework right, and that's the books code or yours
this is just what a exercise in a teach yourself c# book is saying to do ?
Last edited by willmotil; June 22nd, 2014 at 02:21 AM.

5. Junior Member
Join Date
Jun 2014
Posts
4

## Re: How to make these IF statements into a switch

Don't worry I have no one to turn this into. It's all self study!

And like I said in the first post. I was just assuming this was an intro to switch because of how easy it was and the amount of if/else statments I made.

I am using a digital copy of a book but I am on vacation and forgot that I have the book stored on a flash drive so when I took my flash drive out and just took my laptop with me adobe can't load the pages I haven't been on yet so I was only able to read the first 2 pages of this exercise. They must have me be adding stuff to the program that I can't see without my flashdrive. Going from multi class programs to just this seemed really strange to me.

But thanks for helping anyways. Good to know that I really shouldn't be using a switch for this problem.

6. ## Re: How to make these IF statements into a switch

Not that it matters in this example, but another approach is to convert the multiple values into a single value. You can use bit shifting to do this, or in this case an enum with the Flags attribute.
Code:
[Flags]
public enum Choices
{
None = 0,
Healthy = 1,
Fancy = 2,
HeathyAndFancy = 3
}

private void button1_Click(object sender, EventArgs e)
{
...
var choices = Choices.None;

if(cbHealthyOption.Checked)
{
choices |= Choices.Healthy;
}

if(cbFancyOption.Checked)
{
choices != Choices.Fancy;
}

switch(choices)
{
case Choices.Healthy:
// Healthy choices code
break;
case Choices.Fancy:
// Fancy choices code
break;
case Choices.HealthyAndFancy:
// Healthy and fancy choices code
break;
default:
// Neither healthy nor fancy code
}
}

7. ## Re: How to make these IF statements into a switch

As a follow up, it's worth considering about working with separate variables (i.e. healthy and fancy) vs. a single variable (i.e. choices).

Think about what passing several variables in a series of methods requires in terms of future maintenance.
Code:
void Method1(bool p1, bool p2, bool p3, bool p4, ...)
{
Repository.Method1(p1, p2, p3, p4, ...);
}
vs.
Code:
void Method1(Choices choices)
{
Repository.Method1(choices);
}
In the above example, choices is the enum discussed in the previous post. If we convert all the bool variables into a single enum and pass it around in various methods, we will reduce the amount of code we need to change if we need to add additional values. With an enum, we only have to expand the enum declaration (and the logic to set the enum and read from the enum), but we don't need to alter any of the methods that are passing the enum. If we use the Boolean approach, we would need to add new parameter(s) to every method which is more difficult to maintain.

Similarly, we can replace methods containing multiple parameters of different types by passing a class object.

Imagine the following for a person
Code:
void DoSomethingWithPersonMethod(string name, int age, Colors favoriteColor, bool healthy, bool fancy)
{
Respository.DoSomethingWithPersonMethod(name, age, favoriteColor, healther, fancy);
}
vs.

Code:
class Person
{
public string Name { get; set; }
public Colors Colors { get; set; }
public Choices Choices { get; set; }
}

void DoSomethingWithPersonMethod(Person person)
{
Respository.DoSomethingWithPersonMethod(person);
}
If we wanted to expand the Person object, we could redefine it as:
Code:
class Person
{
public string Name { get; set; }
public Colors Colors { get; set; }
public Choices Choices { get; set; }
public string PhoneHome { get; set; }
}
Note that any methods that use a person object would remain unchanged:
Code:
void DoSomethingWithPersonMethod(Person person)
{
Respository.DoSomethingWithPersonMethod(person);
}

8. Junior Member
Join Date
Jun 2014
Posts
4

## Re: How to make these IF statements into a switch

That looks alot more cleaner and a better way of doing it. Thanks for showing me!

9. Member
Join Date
Apr 2014
Location
in northeast ohio
Posts
94

## Re: How to make these IF statements into a switch

Edited: to break down the whole thing into its basic parts
i wanted to point out also that in the context of the example
if you just modify that method a little bit in the first place , it might not be worth bothering to switch it
that example with the if's to switch, well its sort of like concentrating on cleaning up the dust around a pile of dirt.

this is really a good example were...
something that is not really talked about comes into play algorithmic programing or the process of using it.
its sort of a unspoken rule of you learn it/this sometime or as you go
that is... organizing your formula's that are large by breaking them down... its like a unspoken part of oop its implied
breaking parts into variables that change on events, then simplifying your methods for clarity as a side effect.

e.g. getting rid of all those constant variables in the formula
will do more then anything for making that original code readable
getting rid of all those constant values would/should trim the formula down to 2 if statements and 1 if else,
i cant do it here cause i cant see were the -5 *.5 + 30 ect... all relate, which is actually sort of the argument.
but
i can just rearrange it partially just to show
how just moving things around in your original posted formula's
makes it all cleaner right off the bat

Code:
private void button1_Click(object sender, EventArgs e)
{
totalGuests = (int)numericUpDown1.Value;
healthy = cbHealthyOption.Checked;
fancy = cbFancyOption.Checked;

if (healthy && fancy)
totalCost = (totalGuests * 25) + (totalGuests * 5 - ((totalGuests * 5) * .05)) + (totalGuests * 15) + 50;
if (healthy && !fancy)
totalCost = (totalGuests * 25) + (totalGuests * 5 - ((totalGuests * 5) * .05)) + (totalGuests * 7.50) + 30;
if (!healthy && fancy)
totalCost = (totalGuests * 25) + (totalGuests * 20) + (totalGuests * 15) + 50;
if (!healthy && !fancy)
totalCost = (totalGuests * 25) + (totalGuests * 20) + (totalGuests * 7.50) + 30;

if (numericUpDown1.Value == 0)
lblTotal.Text = "\$0";
else
lblTotal.Text = "\$" + totalCost.ToString("#0.00");
}
can we reduce it a bit more we could but ...
in order to do that you have to look at the formula structure
breaking down its parts even not knowing what the formula is
i can break it down and see what is actually happening
by turning the constants into variable names
based on the conditions of the if statements as such....
Code:
private void button1_Click(object sender, EventArgs e)
{
totalGuests = (int)numericUpDown1.Value;
healthy = cbHealthyOption.Checked;
fancy = cbFancyOption.Checked;

float basecalculation = (totalGuests * 30)+30;
float healthyval = ((totalGuests * 5f) * .05f);
float nothealthyval = 15f;
float fancyval = 15f;
float notfancyval =  7.5f;

if (healthy && fancy)
totalCost = basecalculation + (totalGuests  - healthyval ) + (totalGuests * fancyval ) + fancyaddedval ;
if (healthy && !fancy)
totalCost = basecalculation + (totalGuests  - healthyval ) + (totalGuests * notfancyval ) ;
if (!healthy && fancy)
totalCost = basecalculation + (totalGuests * nothealthyval ) + (totalGuests * fancyval ) + fancyaddedval ;
if (!healthy && !fancy)
totalCost = basecalculation + (totalGuests * nothealthyval ) + (totalGuests * notfancyval ) ;

if (numericUpDown1.Value == 0)
lblTotal.Text = "\$0";
else
lblTotal.Text = "\$" + totalCost.ToString("#0.00");
}

// from here we can describe now the component parts and see the structure of the formula
// we see that the primary difference in the formula is healthy or not healthy fancy is just a addition to the basic formula
// so lets re-describe it yet again

private void button1_Click(object sender, EventArgs e)
{
totalGuests = (int)numericUpDown1.Value;
healthy = cbHealthyOption.Checked;
fancy = cbFancyOption.Checked;

// this is the break down of all those constants and the operations we removed them out of the confusing formula
// and turned them into linear math and minimal logic

// as we can now see 4 of these are flat out class constants

float fancyval = 15f;
float notfancyval =  7.5f;
float nothealthyval = 15f;

// these two are method scope variables that vary by totalGuests only
// so they should be probably be some sort of fields or properties
// set by methods fired from events or they could be left here

float healthyval = (float)((totalGuests * 5f) * .05f);
float basecalculation = (float)((totalGuests * 30) + 30);

// on the fly conditional variables to the formula below we could just call them a b c  they belong here

float multme = notfancyval * totalGuests;
float inneroperationme = (totalGuests * nothealthyval );

// so then here is minimal logic it belongs here

if(fancy)
{
multme = fancyval * totalGuests;
}
if(healthy)
float inneroperationme = (totalGuests  - healthyval);

// the actual equation it belongs here

totalCost = basecalculation + inneroperationme  + multme + addme;
}
Last edited by willmotil; June 22nd, 2014 at 09:52 PM.

10. Junior Member
Join Date
Jun 2014
Posts
4

## Re: How to make these IF statements into a switch

Here is a summary from the book of what the program is for.

Kathleen’s Party Planning Program—Cost Estimate for a Dinner Party
• For each person on the guest list there’s a \$25 food charge.
• Clients have a choice when it comes to drinks. Most parties serve alcohol, which
costs \$20 per person. But they can also choose to have a party without alcohol.
Kathleen calls that the “Healthy Option,” and it only costs \$5 per person to have
soda and juice instead of alcohol. Choosing the Healthy Option is a lot easier for
her, so she gives the client a 5% discount on the entire party, too.
• There are two options for the cost of decorations. If a client goes with the
normal decorations, it’s \$7.50 per person with a \$30 decorating fee. A client can
also upgrade the party decorations to the “Fancy Decorations”—that costs \$15
per person with a \$50 one-time decorating fee.

11. Member
Join Date
Apr 2014
Location
in northeast ohio
Posts
94

## Re: How to make these IF statements into a switch

well i was bored and i wrote this and then a modification out for your example i used the [flags] enums
left in your example exercise notes and just coded around them
you can probably see how it would fit into winforms as buttons by the method names

btw kathleen's party is not cheap
(sorry i had a copy paste booboo in there if you saw it when i first posted)

Party People: 4
Total cost: \$240

Party People: 4
Fancy value 2
Healthy value 1
Discount: %0.05000001
Total cost: \$218.5

Party People: 4
Healthy value 1
Discount: %0.05000001
Total cost: \$171

Party People: 4
Fancy value 2
Total cost: \$290

Code:
class Program
{
static void Main(string[] args)
{
PartyTest();
//OtherTests();
}
public static void PartyTest()
{
KathleensCostEstimate someParty = new KathleensCostEstimate();
someParty.DoOnPartyTotalPeopleChanged(4);
someParty.RingUpTotalPrice();
//
KathleensCostEstimate someOtherParty = new KathleensCostEstimate();
someOtherParty.DoOnHealthyClicked();
someOtherParty.DoOnFancyClicked();
someOtherParty.DoOnPartyTotalPeopleChanged(4);
someOtherParty.RingUpTotalPrice();

// lets say they changed there mind on fancy
someOtherParty.DoOnFancyClicked();
someOtherParty.RingUpTotalPrice();

// lets say they changed there mind again
someOtherParty.DoOnFancyClicked();
someOtherParty.DoOnHealthyClicked();
someOtherParty.RingUpTotalPrice();
}

//Kathleen’s Party Planning Program—Cost Estimate for a Dinner Party
public class KathleensCostEstimate
{
private float totalPeople = 6f;
private float totalCost = 0f;
//• For each person on the guest list there’s a \$25 food charge.
private float foodCharge = 25f;
//• Clients have a choice when it comes to drinks.“Healthy Option,”
//• There are two options for the cost of decorations. “Fancy Decorations”
[Flags]
enum Options
{
None = 0,
Healthy = 1,
Fancy = 2
}
Options healthy = Options.None;
Options fancy = Options.None;
Options selection = 0;
// Most parties serve alcohol, which
//costs \$20 per person.
private float drinksAlchoholPerPerson = 20f;
//But they can also choose to have a party without alcohol.
//Kathleen calls that the “Healthy Option,” and it only costs \$5 per person to have soda and juice
private float drinksHealthyPerPerson = 5f;
//instead of alcohol. Choosing the Healthy Option is a lot easier for her,
//so she gives the client a 5% discount on the entire party, too.
private float healthyDiscount = .95f;
private float alcoholDiscount = 1.00f;
//• There are two options for the cost of decorations. If a client goes with the
//normal decorations, it’s \$7.50 per person
private float normalDecorationsPerPerson = 7.50f;
// with a \$30 decorating fee.
private float normalDecorationFee = 30f;
//  A client can also upgrade the party decorations to the “Fancy Decorations”—that costs \$15 per person
private float fancyDecorationsPerPerson = 15f;
// with a \$50 one-time decorating fee.
private float fancyDecorationsFee = 50f;

public void DoOnHealthyClicked()
{
if (healthy == Options.Healthy)
healthy = Options.None;
else
healthy = Options.Healthy;
//
// this symbol | is called an or using it is known as or-ing in this case
// heres what it does in binary each position is worth 2 x the last if either bit is on it goes into the result
// combine bits,  00000010 | 00000001 = 00000011 = 3 decimal  ,(values at each position 128,64,32,16,8,4,2,1)
//
selection = healthy | fancy;
}
public void DoOnFancyClicked()
{
if (fancy == Options.Fancy)
fancy = Options.None;
else
fancy = Options.Fancy;
selection = healthy | fancy; // combine bits
}
// if we remove all of this right down to find total function calculation to the DoOnClicked methods
// pulling the variables within out to be private to the class we can then eliminate the switch case
// we instead end up with an if else that activates on each button click
private float FindTotal(float totalpeople)
{
selection = healthy | fancy;
// default or the case of none we can then just fall thru it
float drinktotal = drinksAlchoholPerPerson * totalpeople;
float discount = alcoholDiscount;
float decortotal = normalDecorationsPerPerson * totalpeople;
float docorfee = normalDecorationsFee;
// override the defaults in this case
switch (selection)
{
case Options.Healthy:
drinktotal = drinksHealthyPerPerson * totalpeople;
discount = healthyDiscount;
break;
case Options.Fancy:
decortotal = fancyDecorationsPerPerson * totalpeople;
docorfee = fancyDecorationFee;
break;
case Options.Healthy | Options.Fancy:
drinktotal = drinksHealthyPerPerson * totalpeople;
discount = healthyDiscount;
decortotal = fancyDecorationsPerPerson * totalpeople;
docorfee = fancyDecorationFee;
break;
default: break;
}
// the total
return (totalPeople * foodCharge + drinktotal + decortotal + docorfee) * discount;
}
public void DoOnPartyTotalPeopleChanged(int n)
{
//totalPeople = button_ blahlblahtotalpeopleclicked
totalPeople = n;
}
public float RingUpTotalPrice()
{
totalCost = FindTotal(totalPeople);
string str = "\n Party People: " + totalPeople;
str += "\n Accomidations " + selection + " value "+ (int)selection;
if (selection.HasFlag(Options.Healthy))
str += "\n Discount: %" + (1f - healthyDiscount).ToString();
str += "\n Total cost: \$" + totalCost.ToString();
Console.WriteLine(str);
}
}
}

// so then here is another way to do it
// basically split up the switches you could make separate enum options

class Program
{
static void Main(string[] args)
{
PartyTest();
//OtherTests();
}
public static void PartyTest()
{
KathleensCostEstimate someParty = new KathleensCostEstimate();
someParty.DoOnPartyTotalPeopleChanged(4);
someParty.RingUpTotalPrice();
//
KathleensCostEstimate someOtherParty = new KathleensCostEstimate();
someOtherParty.DoOnHealthyClicked();
someOtherParty.DoOnFancyClicked();
someOtherParty.DoOnPartyTotalPeopleChanged(4);
someOtherParty.RingUpTotalPrice();

// lets say they changed there mind on fancy
someOtherParty.DoOnFancyClicked();
someOtherParty.RingUpTotalPrice();

// lets say they changed there mind again
someOtherParty.DoOnFancyClicked();
someOtherParty.DoOnHealthyClicked();
someOtherParty.RingUpTotalPrice();
}

//Kathleen’s Party Planning Program—Cost Estimate for a Dinner Party
public class KathleensCostEstimate
{
private float totalPeople = 6f;
private float totalCost = 0f;
private float foodCharge = 25f;
[Flags]
enum PartyMemberOptions
{
None = 0,
Healthy = 1,
Fancy = 2
}
PartyMemberOptions healthy = PartyMemberOptions.None;
PartyMemberOptions fancy = PartyMemberOptions.None;
private float drinksAlchoholPerPerson = 20f;
private float drinksHealthyPerPerson = 5f;
private float healthyDiscount = .95f;
private float alcoholDiscount = 1.00f;
private float normalDecorationsPerPerson = 7.50f;
private float normalDecorationFee = 30f;
private float fancyDecorationsPerPerson = 15f;
private float fancyDecorationsFee = 50f;

float drinktotal = 0;
float discount = 0;
float decortotal = 0;
float docorfee = 0;

public void DoOnPartyTotalPeopleChanged(int n)
{
totalPeople = n;
}
public void DoOnHealthyClicked()
{
if (healthy == PartyMemberOptions.Healthy)
healthy = PartyMemberOptions.None;
else
healthy = PartyMemberOptions.Healthy;
}
public void DoOnFancyClicked()
{
if (fancy == PartyMemberOptions.Fancy)
fancy = PartyMemberOptions.None;
else
fancy = PartyMemberOptions.Fancy;
}
public void HealthyChanges()
{
switch (healthy)
{
case PartyMemberOptions.Healthy:
drinktotal = drinksHealthyPerPerson * totalPeople;
discount = healthyDiscount;
break;
default:
drinktotal = drinksAlchoholPerPerson * totalPeople;
discount = alcoholDiscount;
break;
}
}
public void FancyChanges()
{
switch (fancy)
{
case PartyMemberOptions.Fancy:
decortotal = fancyDecorationsPerPerson * totalPeople;
docorfee = fancyDecorationsFee;
break;
default:
decortotal = normalDecorationsPerPerson * totalPeople;
docorfee = normalDecorationFee;
break;
}
}

private float FindTotal(float totalpeople)
{
FancyChanges();
HealthyChanges();
return (totalPeople * foodCharge + drinktotal + decortotal + docorfee) * discount;
}
public float RingUpTotalPrice()
{
totalCost = FindTotal(totalPeople);
string str = "\n Party People: " + totalPeople;
if (fancy.HasFlag(PartyMemberOptions.Fancy))
{
str +=
"\n Fancy value "+
(int)fancy
;
}
if (healthy.HasFlag(PartyMemberOptions.Healthy))
{
str +=
"\n Healthy value " +
(int)healthy +
"\n Discount: %" +
(1f - healthyDiscount).ToString()
;
}
str += "\n Total cost: \$" + totalCost.ToString();
Console.WriteLine(str);
}
}
}
Last edited by willmotil; June 23rd, 2014 at 02:14 AM.

12. ## Re: How to make these IF statements into a switch

I think that calculating the cost of the party is a good candidate for a function that would looks like this:

Code:
private double GetPartyCost(uint totalGuests, bool healthy, bool fancy)
{
double drinksCost = 20;
double discount = 0;
double decorationsCost = 7.5;
double decoratingFee = 30;

if (healthy)
{
drinksCost = 5;
discount = 0.05;
}

if (fancy)
{
decorationsCost = 15;
decoratingFee = 50;
}

double totalCost = (totalGuests * 25.0 + (totalGuests * drinksCost) + totalGuests * decorationsCost + decoratingFee) * (1 - discount);

}
I've applied the discount for the entire party, which will give you different result than your original code, but overall, the main idea is to avoid copying the whole formula at multiple place.

JeffB

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•