Passing Different Classes to Same Method - c#

I'm setting up a little "shop" system for a small self-teaching project. I can get it to work if I define each class argument accepted by the form, but what if I want to pass different classes with different properties?
Here is my item class, each with different properties.
public class Items
{
public int ID { get; set; }
public string ItemName { get; set; }
public int ItemType { get; set; }
public int GoldValue { get; set; }
}
public class Weapons : Items
{
public int MinDamage { get; set; }
public int MaxDamage { get; set; }
public Weapons(int id, string itemName, int itemType, int goldValue, int minDamage, int maxDamage)
{
ID = id;
ItemName = itemName;
ItemType = itemType;
GoldValue = goldValue;
MinDamage = minDamage;
MaxDamage = maxDamage;
}
}
public class Armors : Items
{
public int Defense { get; set; }
public Armors(int id, string itemName, int itemType, int goldValue, int defense)
{
ID = id;
ItemName = itemName;
ItemType = itemType;
GoldValue = goldValue;
Defense = defense;
}
}
public class Shields : Items
{
public int Defense { get; set; }
public Shields(int id, string itemName, int itemType, int goldValue, int defense)
{
ID = id;
ItemName = itemName;
ItemType = itemType;
GoldValue = goldValue;
Defense = defense;
}
}
public class Potions : Items
{
public int HPHeal { get; set; }
public int MPHeal { get; set; }
public int SPHeal { get; set; }
public Potions(int id, string itemName, int itemType, int goldValue, int hpHeal, int mpHeal, int spHeal)
{
ID = id;
ItemName = itemName;
ItemType = itemType;
GoldValue = goldValue;
HPHeal = hpHeal;
MPHeal = mpHeal;
SPHeal = spHeal;
}
}
Here is my Shop form.
public partial class Shop : Form
{
Weapons item1;
Armors item2;
Shields item3;
int Gold;
public Shop(int gold, Weapons weapon1, Armors armor1, Shields shield1)
{
InitializeComponent();
item1 = weapon1;
item2 = armor1;
Gold = gold;
item1Lbl.Text = item1.ItemName + " " + item1.MinDamage + " - " + item1.MaxDamage + " Damage -- " + item1.GoldValue + " Gold";
item2Lbl.Text = item2.ItemName + " " + item2.Defense + " Defense -- " + item2.GoldValue + " Gold";
item3Lbl.Text = item3.ItemName + " " + item3.Defense + " Defense -- " + item3.GoldValue + " Gold";
}
public Shop(int gold, Potions potion1, Potions potion2, Potions potion3)
{
}
private void Shop_Load(object sender, EventArgs e)
{
}
private void buy1Btn_Click(object sender, EventArgs e)
{
if (Gold >= item1.GoldValue)
{
Equipment.ChangeWeapon(item1.ID, item1.ItemName, item1.MinDamage, item1.MaxDamage);
Equipment.Gold -= item1.GoldValue;
this.Close();
}
else
{
MessageBox.Show("You need " + (item1.GoldValue - Gold) + " additional gold.");
}
}
private void buy2Btn_Click(object sender, EventArgs e)
{
if (Gold >= item2.GoldValue)
{
Equipment.ChangeArmor(item2.ID, item2.ItemName, item2.Defense);
Equipment.Gold -= item2.GoldValue;
this.Close();
}
else
{
MessageBox.Show("You need " + (item2.GoldValue - Gold) + " additional gold.");
}
}
private void buy3Btn_Click(object sender, EventArgs e)
{
if (Gold >= item3.GoldValue)
{
Equipment.ChangeShield(item3.ID, item3.ItemName, item3.Defense);
Equipment.Gold -= item3.GoldValue;
this.Close();
}
else
{
MessageBox.Show("You need " + (item3.GoldValue - Gold) + " additional gold.");
}
}
}
What would be an efficient way to set it up so that I can pass any item type (Weapons, Armors, Potions, etc) to the same form without having to write code explicitly for each possibility?

Related

Calculate Price Method Not Working In Visual Studio

So I've made this form that acts as a cake shop. I have everything working perfectly except for the price. For some reason it isn't displaying properly and shows "$22.60" every time. I'm thinking there might be something wrong with the method
public virtual double CalculateCakeCost()
{
return CAKE_PRICE + (LAYER_PRICE * NumOfLayers);
}
from class "Cake" since it seems to return the cake price, but not add it up with the bracket values. The calculate cost with tax method from the class "CustomCake" also seems to be working fine. You can read the rest of the code is down below and please tell me if there is a problem, because I don't see anything wrong.
namespace Lab_OrderCake_The_Bakery_
{
public partial class frmOrderCake : Form
{
Cake objcake;
CustomCake objcustcake;
Customer objcustomer;
Order objorder;
public frmOrderCake()
{
InitializeComponent();
}
private void btnOrder_Click(object sender, EventArgs e)
{
//flavour
if (radVanilla.Checked == true)
{
txtRadFlavour.Text = "Vanilla";
}
if (radChocolate.Checked == true)
{
txtRadFlavour.Text = "Chocolate";
}
if (radBanana.Checked == true)
{
txtRadFlavour.Text = "Banana";
}
if (radLemonBerry.Checked == true)
{
txtRadFlavour.Text = "Lemon banana";
}
//layers
if (rad1layer.Checked == true)
{
numRadLayers.Value = 1;
}
if (rad2layers.Checked == true)
{
numRadLayers.Value = 2;
}
if (rad3layers.Checked == true)
{
numRadLayers.Value = 3;
}
if (rad4layers.Checked == true)
{
numRadLayers.Value = 4;
}
//occassion
if (radAnniversary.Checked == true)
{
txtRadOcc.Text = "Anniversary";
}
if (radBirthday.Checked == true)
{
txtRadOcc.Text = "Birthday";
}
if (radRetirement.Checked == true)
{
txtRadOcc.Text = "Retirement";
}
if (radWedding.Checked == true)
{
txtRadOcc.Text = "Wedding";
}
//size
if (rad6inch.Checked == true)
{
numRadSize.Value = 6;
}
if (rad8inch.Checked == true)
{
numRadSize.Value = 8;
}
if (rad10inch.Checked == true)
{
numRadSize.Value = 10;
}
if (rad12inch.Checked == true)
{
numRadSize.Value = 12;
}
//design
if (radPolka.Checked == true)
{
txtRadDesign.Text = "Polka Dots";
}
if (rad8inch.Checked == true)
{
txtRadDesign.Text = "Edible Images";
}
if (rad10inch.Checked == true)
{
txtRadDesign.Text = "Fondant Bow";
}
if (rad12inch.Checked == true)
{
txtRadDesign.Text = "3D Figures";
}
objcake = new Cake(txtRadFlavour.Text, (int)numRadLayers.Value);
objcustomer = new Customer(txtFName.Text, txtLName.Text);
objcustcake = new CustomCake(txtRadFlavour.Text, (int)numRadLayers.Value, txtRadOcc.Text,
(int)numRadSize.Value, txtRadDesign.Text);
objorder = new Order();
lblOutOrder.Text = objcustomer.ToString() + objcustcake.ToString() + objorder.ToString();
}
}
namespace CakeClasses
{
public class Cake
{
public int NumOfLayers { get; set; }
public string Flavour { get; set; }
public double Price { get; set; }
public const double CAKE_PRICE = 20;
public const int LAYER_PRICE = 3;
public Cake()
{
Flavour = "";
NumOfLayers = 0;
}
public Cake(string flavour, int numLayers)
{
NumOfLayers = numLayers;
Flavour = flavour;
}
**public virtual double CalculateCakeCost()
{
return CAKE_PRICE + (LAYER_PRICE * NumOfLayers);
}**
public override string ToString()
{
return " " + Flavour + " flavoured cake with " + NumOfLayers + " layer(s)";
}
}
}
namespace CakeClasses
{
public class Order
{
public Customer Customer { get; set; }
public Cake Cake { get; set; }
public int NumOfCakes { get; set; }
public Order()
{
Customer = new Customer();
Cake = new Cake();
NumOfCakes = 1;
}
public Order(string fName, string lName, string flavour, int numLayers, string occasion, int
diameter, string design)
{
Customer = new Customer(fName, lName);
Cake = new CustomCake(flavour, numLayers, occasion,diameter,design);
NumOfCakes = 1;
}
public Order(string fName, string lName, string flavour, int numLayers)
{
Customer = new Customer(fName, lName);
Cake = new Cake(flavour, numLayers);
NumOfCakes = 1;
}
public double CalculateCostWithTax()
{
return Cake.CalculateCakeCost() * 1.13;
}
public override string ToString()
{
return "for the total cost of " + CalculateCostWithTax().ToString("C");
}
}
}
namespace CakeClasses
{
public class CustomCake : Cake
{
public string Occasion { get; set; }
public int Size { get; set; }
public string Design { get; set; }
private double DesignCost { get; set; }
public CustomCake(string flavour, int numLayers,string occasion, int diameter, string design)
:base(flavour,numLayers)
{
Occasion = occasion;
Size = diameter;
Design = design;
switch (Design)
{
case "Polka Dots":
DesignCost = 5;
break;
case "Edible Images":
DesignCost = 12;
break;
case "Fondant Bow":
DesignCost = 10;
break;
default:
DesignCost = 15;
break;
}
}
public override double CalculateCakeCost()
{
return base.CalculateCakeCost() + Size + DesignCost;
}
public override string ToString()
{
return base.ToString() + " with " + Design + " design for " + Occasion + " occassion and
size is " + Size + " inches " ;
}
}
}
Try replacing following line in your code:
objorder = new Order();
with:
objorder = new Order("First Name","Last Name",txtRadFlavour.Text, (int)numRadLayers.Value);

How to get variabels from Class x and set them at Class y

For school im makeing a online shop application. i have 2 listboxes, one with products and one that is like a shopping cart:
Now i have the following classes:
public class Artikel
{
// instantie variabelen
private string artikelnaam;
private string categorie;
private double prijs;
// properties
public string Artikelnaam { get; }
public string Categorie { get; }
public double Prijs { get; }
// constructor
public Artikel(string artikelnaam, string categorie, double prijs)
{
this.artikelnaam = artikelnaam;
this.categorie = categorie;
this.prijs = prijs;
}
// ToString methode
public override string ToString()
{
return artikelnaam + "\t" + categorie + "\t" + prijs;
}
}
and the shopping cart class:
class WinkelwagenObject
{
// instantie variabelen
private string artikelnaam;
private string categorie;
private int aantal;
private double prijs;
private double subtotaal;
// properties
public string Artikelnaam { get; }
public string Categorie { get; }
public int Aantal { get; set; }
public double Prijs { get; }
public double Subtotaal { get; }
// constructor
public WinkelwagenObject(string artikelnaam, string categorie, int aantal, double prijs, double subtotaal)
{
this.artikelnaam = artikelnaam;
this.categorie = categorie;
this.aantal = aantal;
this.prijs = prijs;
this.subtotaal = subtotaal;
}
// ToString methode
public override string ToString()
{
return artikelnaam + "\t" + categorie + "\t" + aantal + "\t" + prijs + "\t" + subtotaal;
}
Now how do i selected a product in the lb of the products and send it too the shopping cart with the button "toevoegen"
You could make an Add-Method to the your Cart-Class that recieves an Artikel-Object and puts it into an Artikel-Collection like this:
public List<Artikel> ArtikelList { get; private set; }
public void Add(Artikel artikel)
{
if (ArtikelList == null)
ArtikelList = new List<Artikel>();
ArtikelList.Add(artikel);
}

How to list a list of classes in a listbox?

I want to make a list with person's names, in a listbox. The names should be added using the textbox, and i am using a class for the name savement etc.
How can i show the name of the person that added info to a listbox, and only show the information to a richtextbox when the list is clicked/pressed?
class code
class Persoon
{
private string naam;
private string geslacht;
private double gewicht;
private double lengte;
public double bmi;
public string Naam
{
get { return naam; }
set { naam = value; }
}
public string Geslacht
{
get { return geslacht; }
set { geslacht = value; }
}
public double Gewicht
{
get { return gewicht; }
set { gewicht = value; }
}
public double Lengte
{
get { return lengte; }
set { lengte = value; }
}
public double Bmi
{
get { return bmi; }
set { bmi = value; }
}
public object Convert { get; internal set; }
public Persoon(string nm, string gt, int wt, int le)
{
naam = nm;
geslacht = gt;
gewicht = wt;
lengte = le;
}
public double BMI()
{
double bmiuitkomst = gewicht / Math.Pow(lengte / 100.0, 2);
return bmiuitkomst;
}
public override string ToString()
{
return "Persoon: " + Naam + " " + Geslacht;
}
form code
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string naam = tb_naam.Text;
string geslacht = tb_geslacht.Text;
double gewicht = Convert.ToDouble(tb_gewicht.Text);
double lengte = Convert.ToDouble(tb_lengte.Text);
double bmiuitkomst = gewicht / Math.Pow(lengte / 100.0, 2);
Persoon nieuwbmi = new Persoon(naam, geslacht, Convert.ToInt32(gewicht), Convert.ToInt32(lengte));
rtb_uitkomst.Text = "Naam: "+ naam + Environment.NewLine + "Geslacht: " + geslacht + Environment.NewLine + "BMI: " + Convert.ToString(bmiuitkomst);
// rtb_uitkomst.Text = nieuwbmi.ToString();
List<string> uitkomsten = new List<string>();
foreach (var item in uitkomsten)
{
uitkomsten.Add(Convert.ToString(nieuwbmi));
}
// lb_list.(Convert.ToString(nieuwbmi));
lb_list.DataSource = uitkomsten;
}
}
thanks in advance.
You are declaring a variable uitkomsten locally in button1_Click. This variable exists only while the method is executed. To make it live during the whole lifetime of the form, declare it as a field of the form class (and remove the declaration from the button1_Click method)
public partial class Form1 : Form
private List<string> uitkomsten = new List<string>();
public Form1()
{
InitializeComponent();
}
...
}
Then you try to add a person with
foreach (var item in uitkomsten)
{
uitkomsten.Add(Convert.ToString(nieuwbmi));
}
This cannot work. The foreach loop loops as many times as there are elements in the uitkomsten list. But since the list is empty at the beginning, the Add method will never be executed. Remove the loop.
uitkomsten.Add(Convert.ToString(nieuwbmi));
Note that you could add persons directly to the list, if you had a List<Persoon>. The listbox automatically uses .ToString() to display objects.
uitkomsten.Add(nieuwbmi);
Another problem is that lb_list.DataSource = uitkomsten; always assigns the same list. Because of how the listbox is implemented, it does not notice any difference and will therefore not display new persons added. To work around this problem, assign null first.
lb_list.DataSource = null;
lb_list.DataSource = uitkomsten;
Also change the weight and length parameters to double in the constructor of Persoon. You have doubles everywhere else for these measurements. If you use auto-implemented properties, this simplifies the class
class Persoon
{
public string Naam { get; set; }
public string Geslacht { get; set; }
public double Gewicht { get; set; }
public double Lengte { get; set; }
public double Bmi { get; set; }
public Persoon(string nm, string gt, double wt, double le)
{
Naam = nm;
Geslacht = gt;
Gewicht = wt;
Lengte = le;
}
public double BMI()
{
return Gewicht / Math.Pow(Lengte / 100.0, 2);
}
public override string ToString()
{
return $"Persoon: {Naam} {Geslacht}";
}
}
The form then becomes (with a few additional tweaks)
public partial class Form1 : Form
{
private List<Persoon> uitkomsten = new List<Persoon>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string naam = tb_naam.Text;
string geslacht = tb_geslacht.Text;
double gewicht = Convert.ToDouble(tb_gewicht.Text);
double lengte = Convert.ToDouble(tb_lengte.Text);
Persoon nieuwbmi = new Persoon(naam, geslacht, gewicht, lengte);
rtb_uitkomst.Text = $"Naam: {naam}\r\nGeslacht: {geslacht}\r\nBMI: {nieuwbmi.BMI()}";
uitkomsten.Add(nieuwbmi);
lb_list.DataSource = null;
lb_list.DataSource = uitkomsten;
}
}
private List<string> uitkomsten = new List<string>();
private BindingSource bs = new BindingSource();
public MainForm()
{
InitializeComponent();
bs.DataSource = uitkomsten;
lb_list.DataSource = bs;
}
private void button1_Click(object sender, EventArgs e)
{
......
uitkomsten.Add(Convert.ToString(nieuwbmi));
bs.ResetBindings(false);
}
How can i make sure it only displays the info in the richtextbox when the name is selected (in the listbox)?
private void lb_list_SelectedIndexChanged(object sender, EventArgs e)
{
Persoon nieuwbmi = ((Persoon)lb_list.SelectedItem).Name1;
rtb_uitkomst.Text = "Naam: " + naam + Environment.NewLine + "Geslacht: " + geslacht + Environment.NewLine + "BMI: " + Convert.ToString(bmiuitkomst);
}

How to return enum value name to property in c#

First, i'm a beginning in c#. I'm try to code some game. I don't know how to return enum value as string.
Here my code.
public class CARDS {
public CARDS(int id, int atk, ClassType ctype, string name) {
this.CARD_ID = id;
this.C_TYPE = ctype;
this.ATK = atk;
this.NAME_EN = name;
}
public CARDS() {
this.CARD_ID = -1;
}
public int CARD_ID { get; set; }
public ClassType C_TYPE { get; set; }
public int ATK { get; set; }
public string NAME_EN { get; set; }
public enum ClassType {
Warrior,
Mage,
Archer,
Thief,
Bishop,
Monk,
Guardian,
Destroyer,
Chaser,
Hermit,
Alchemy
}
}
.......
Here I try to do.
public class CardCollection : MonoBehaviour {
private List<CARDS> dbase = new List<CARDS>();
private JsonData cardsdata;
private JsonData card;
void Start() {
cardsdata = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/Json/card.json"));
ConstructCardData();
Debug.Log(dbase[1].NAME_EN + " " + dbase[23].NAME_EN);
}
void ConstructCardData() {
card = cardsdata["CARDS"];
for (int i = 0; i < card.Count; i++) {
dbase.Add(new CARDS((int)card[i]["CARD_ID"], (int)card[i]["ATK"], card[i]["C_TYPE"].ToString(), card[i]["NAME_EN"].ToString()));
}
}
}
// card[i]["C_TYPE"].ToString()
It say can't convert from string to CARDS.ClassType
What about :
public class CARDS
{
public CARDS(int id, int atk, ClassType ctype, string name)
{
this.CARD_ID = id;
this.C_TYPE = Enum.GetName(ctype.GetType(), ctype); //Use Enum.GetName to get string
this.ATK = atk;
this.NAME_EN = name;
}
public CARDS()
{
this.CARD_ID = -1;
}
public int CARD_ID { get; set; }
public string C_TYPE { get; set; } //change type to string
public int ATK { get; set; }
public string NAME_EN { get; set; }
public enum ClassType
{
Warrior,
Mage,
Archer,
Thief,
Bishop,
Monk,
Guardian,
Destroyer,
Chaser,
Hermit,
Alchemy
}
}
ToString() on the enum values return the string value of the enum. Custom string values can also be returned for the enum values, check these links, link1 , link2
Examples:
ClassType.Warrior.ToString();
ctype.ToString();

C# array to save data

I am new with C# and i have a problem. Actually it's my first year in college and in programming and i have a problem with arrays. I've made a class with 3 constructors and 1 method in Windows Form Application. The problem is that i want to store data from three textBoxes - that the user is typing- into an array of 10 using a button. and i don't know how to do it.
public class Employee
{
private int idnum;
private string flname;
private double annual;
public Employee()
{
idnum = 0;
flname = "";
annual = 0.0;
}
public Employee(int id, string fname)
{
idnum = id;
flname = fname;
annual = 0.0;
}
public Employee(int id, string fname, double ann)
{
idnum = id;
flname = fname;
annual = ann;
}
public int idNumber
{
get { return idnum; }
set { idnum = value; }
}
public string FLName
{
get { return flname; }
set { flname = value; }
}
public double Annual
{
get { return annual; }
set { annual = value; }
}
public string Message()
{
return (Convert.ToString(idnum) + " " + flname + " " + Convert.ToString(annual));
}
}
First of all you should add on this form 3 textboxe elements and name it in a next manner textBoxId, textBoxFLName, textBoxAnnual
Also you have to add a button. Let's call it btnSave
Write an event OnClick for this button. In this method we must read all data which user fill in on the form.
List<Employee> allEmployees = new List<Employee>();
private void buttonSave_Click(object sender, EventArgs e)
{
//read user input
int empId = Int32.Parse(textBoxId.Text);
string empFlName = textBoxFLName.Text;
double empAnnual = double.Parse(textBoxAnnual.Text);
// create new Employee object
Employee emp = new Employee(empId, empFlName, empAnnual);
// add new employee to container (for example array, list, etc).
// In this case I will prefer to use list, becouse it can grow dynamically
allEmployees.Add(emp);
}
And you can also rewrite your code in a little bit shortest manner:
public class Employee
{
public int IdNum { get; set; }
public string FlName { get; set; }
public double Annual { get; set; }
public Employee(int id, string flname, double annual = 0.0)
{
IdNum = id;
FlName = flname;
Annual = annual;
}
public override string ToString()
{
return (Convert.ToString(IdNum) + " " + FlName + " " + Convert.ToString(Annual));
}
}

Categories

Resources