Try catch statements with window forms application - c#

My goal is to throw a NegativeBalanceException if there is an attempt to take the balance below zero. Just like if this was a real bank account. I had if and else statements, but butchered them up and am trying to learn try, catch, and throw statements (was reading on finally as well but I don't think that applies here). Anyway, I set up where a catch statement works if I just hit the deposit button without typing anything. But, I don't understand where it is wanting me to implement it in for taking it below zero. Is it in my deposit method? Or is it in the actual btn_deposit? Also, what is the purpose of using try catch statements over if else statements? I am new to programming and am just trying to learn.
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 WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class BankAccount
{
decimal amount = 300.00m;
// Declare Delegate Type Object
public delegate void BankDelegate(decimal oldBalance, decimal newBalance);
// Create Delegate Type Events
public event BankDelegate OnDeposit;
public event BankDelegate OnWithdraw;
public void Deposit(decimal a)
{
{
if (a > 0)
{
OnDeposit(this.amount, this.amount + a);
this.amount += a;
}
else
{
MessageBox.Show("No!");
}
}
}
public void Withdraw(decimal a)
{
// Fire OnWithdraw Event and pass old and new balance amount
OnWithdraw(this.amount, this.amount - a);
this.amount -= a;
}
}
// Declare BankAccount class variable
BankAccount account = null;
private void Form1_Load(object sender, EventArgs e)
{
account = new BankAccount();
// Attach Event Handlers with Events
account.OnDeposit += new BankAccount.BankDelegate(account_OnDeposit);
account.OnWithdraw += new BankAccount.BankDelegate(account_OnWithdraw);
}
private void btnDeposit_Click(object sender, EventArgs e)
{
try
{
account.Deposit(Convert.ToDecimal(textBox1.Text));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnWIthdraw_Click(object sender, EventArgs e)
{
account.Withdraw(Convert.ToDecimal(textBox1.Text));
}
void account_OnDeposit(decimal oldBalance, decimal newBalance)
{
label4.Text = oldBalance.ToString();
label5.Text = newBalance.ToString();
}
void account_OnWithdraw(decimal oldBalance, decimal newBalance)
{
label4.Text = oldBalance.ToString();
label5.Text = newBalance.ToString();
}
}
}

You should only throw exceptions for exceptional circumstances. Overdrawn accounts are not an exceptional circumstance.. but depositing a negative amount is.
Therefore, I would do something like this for the Deposit method:
public void Deposit(decimal a)
{
if (a < 1)
throw new NegativeDepositException("You cannot deposit this amount");
OnDeposit(this.amount, this.amount + a);
this.amount += a;
}
BUT.
You should be validating this prior to entering the method. That way, the exception should never be called - unless you call Deposit from another method without the check - which would be exceptional.
private void btnDeposit_Click(object sender, EventArgs e)
{
// try..catch removed. This will now crash if you forget to check the value.
var amount = Convert.ToDecimal(textBox1.Text);
if (amount < 1)
MessageBox.Show("You cannot deposit this amount");
else
account.Deposit(amount);
}
Also, I would change Withdraw to return bool, since overdrawing is not really an exceptional circumstance:
public bool Withdraw(decimal a)
{
if (this.amount - a >= 0)
{
// Fire OnWithdraw Event and pass old and new balance amount
OnWithdraw(this.amount, this.amount - a);
this.amount -= a;
return true; // successful
}
else
{
return false; // unsuccessful
}
}
Then when you call it:
private void btnWIthdraw_Click(object sender, EventArgs e)
{
if (!account.Withdraw(Convert.ToDecimal(textBox1.Text)))
{
MessageBox.Show("Insufficient funds");
}
}
EDIT:
In response to your comment. You must create your own exception class if you want it to be named a specific way (or if you want it to extend the functionality of a normal Exception). In my example, you would have to create this:
public class NegativeDepositException : Exception {
}
Thats it. It gets everything it needs from Exception.. for now.

Related

Firing events in C++ and handling them in C#

I have an industrial computer with some Digital I/O pins. The manufacturer provides some C++ libraries and examples to handle pin status change.
I need to integrate this events onto a C# application. AFAIK the most simple way to perform this is:
Make a managed C++/CLI wrapper for the manufacturer libraries that fires events when interruptions are issued from the DIO pins.
Reference that wrapper and handle the events in the C# part as it they were normal C# events.
I have tried to make this work with some mock objects with no luck. From the docs, the function EventHandler should do most of the "dirty work" in my case. Following info available in old threads and the EventHandler example in the MSDN docs I ended up with this test code:
C++/CLI
using namespace System;
public ref class ThresholdReachedEventArgs : public EventArgs
{
public:
property int Threshold;
property DateTime TimeReached;
};
public ref class CppCounter
{
private:
int threshold;
int total;
public:
CppCounter() {};
CppCounter(int passedThreshold)
{
threshold = passedThreshold;
}
void Add(int x)
{
total += x;
if (total >= threshold) {
ThresholdReachedEventArgs^ args = gcnew ThresholdReachedEventArgs();
args->Threshold = threshold;
args->TimeReached = DateTime::Now;
OnThresholdReached(args);
}
}
event EventHandler<ThresholdReachedEventArgs^>^ ThresholdReached;
protected:
virtual void OnThresholdReached(ThresholdReachedEventArgs^ e)
{
ThresholdReached(this, e);
}
};
public ref class SampleHandler
{
public:
static void c_ThresholdReached(Object^ sender, ThresholdReachedEventArgs^ e)
{
Console::WriteLine("The threshold of {0} was reached at {1}.",
e->Threshold, e->TimeReached);
Environment::Exit(0);
}
};
void main()
{
return;
CppCounter^ c = gcnew CppCounter(20);
c->ThresholdReached += gcnew EventHandler<ThresholdReachedEventArgs^>(SampleHandler::c_ThresholdReached);
Console::WriteLine("press 'a' key to increase total");
while (Console::ReadKey(true).KeyChar == 'a') {
Console::WriteLine("adding one");
c->Add(1);
}
}
C#
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
CppCounter cc = new CppCounter(5);
//cc.ThresholdReached += cs_ThresholdReached; //<--This is the offending line
Console.WriteLine("press 'a' key to increase total");
while (Console.ReadKey(true).KeyChar == 'a')
{
Console.WriteLine("adding one");
cc.Add(1);
}
}
static void cs_ThresholdReached(object sender, ThresholdReachedEventArgs e)
{
Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached);
Environment.Exit(0);
}
}
class Counter
{
private int threshold;
private int total;
public Counter(int passedThreshold)
{
threshold = passedThreshold;
}
public void Add(int x)
{
total += x;
if (total >= threshold)
{
ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
args.Threshold = threshold;
args.TimeReached = DateTime.Now;
OnThresholdReached(args);
}
}
protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
{
EventHandler<ThresholdReachedEventArgs> handler = ThresholdReached;
if (handler != null)
{
handler(this, e);
}
}
public event EventHandler<ThresholdReachedEventArgs> ThresholdReached;
}
public class ThresholdReachedEventArgs : EventArgs
{
public int Threshold { get; set; }
public DateTime TimeReached { get; set; }
}
}
What am I doing wrong? Is it something I am missing?
public class ThresholdReachedEventArgs : EventArgs
The code is correct, except for this minor glitch. You accidentally re-declared this class in your C# code. Now there are two, one from your C++/CLI project and another from your C# project. That is a problem, type identity in .NET is not just determined by the namespace name and class name, it also includes the assembly it came from.
So these are two distinct types, the compiler tries to tell you that the C# version of it is not the correct one. That they have the same name doesn't exactly help you decode the error message :)
Very easy to fix, simply delete the class declaration from your C# code. Now the compiler will use the C++/CLI version of it.

C# Class scope issue?

I am a student. This is our first project using two different class files, and it is also only the second one using Forms. So, I don't have much experience with either.
The object is declared and instantiated, but the object is not recognized in any of the subsequent methods. I am following the code on the book. The code on the book declares/instantiates like this:
new Order = new Order( );
I think it needs to be like this, but that still doesn't help the subsequent references:
Order newOrder = new Order( );
This a a complete listing of the driver and the two class files:
Driver:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Diner
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new OrderGUI());
}
}
}
OrderGUI.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Diner
{
public partial class OrderGUI : Form
{
public OrderGUI()
{
InitializeComponent();
}
//For Load - create object
private void OrderGUI_Load(object sender, System.EventArgs e)
{
newOrder = new Order();
for (int i = 0; i < newOrder.menuEntree.Length; i++)
{
this.lstBxEntree.Items.Add(newOrder.menuEntree[i]);
}
}
// Event handler that gets the entree from the
// Listbox and sets the entree price of the Order object.
private void lstBxEntree_SelectedIndexChanged
(object sender, System.EventArgs e)
{
newOrder.Entree = this.lstBxEntree.Text;
}
// Event handler that gets the special request -
// if one is selected from the predefined list.
private void cmboSpecial_SelectedIndexChanged
(object sender, System.EventArgs e)
{
newOrder.SpecialRequest = this.cmboSpecial.Text;
}
// Menu item that displays the order.
private void menuDisplayOrder_Click(object sender,
System.EventArgs e)
{
}
// Event handler that gets the radio button selected and
// sets the drink selection for the Order object
private void Drink_CheckedChanged(object sender,
System.EventArgs e)
{
if (this.radTea.Checked)
newOrder.DrinkSelection = radTea.Text;
else
if (this.radCoffee.Checked)
newOrder.DrinkSelection = radCoffee.Text;
else
if (this.radSoda.Checked)
newOrder.DrinkSelection = radSoda.Text;
else
if (this.radLemon.Checked)
newOrder.DrinkSelection = radLemon.Text;
else
if (this.radJuice.Checked)
newOrder.DrinkSelection = radJuice.Text;
else
if (this.radMilk.Checked)
newOrder.DrinkSelection = radMilk.Text;
}
// Event handler that gets raised when the check box
// for the Water gets clicked.
private void ckBxWater_CheckedChanged
(object sender, System.EventArgs e)
{
if (this.ckBxWater.Checked)
newOrder.WaterSelection = true;
else
newOrder.WaterSelection = false;
}
// Event handler that gets raised when the user types
// values into the text area of the combo box.
private void cmboSpecial_KeyPress
(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
newOrder.SpecialRequest = this.cmboSpecial.Text;
}
// Event handler that gets raised when the Edit menu
// is clicked to change the entree.
private void menuEditEntree_Click
(object sender, System.EventArgs e)
{
}
// Event handler that gets raised when the Edit menu
// is clicked to change the drink.
private void menuEditDrink_Click
(object sender, System.EventArgs e)
{
}
// Clears selections for all drink radio buttons.
public void ClearDrinks()
{
this.radMilk.Checked = false;
this.radJuice.Checked = false;
this.radSoda.Checked = false;
this.radLemon.Checked = false;
this.radTea.Checked = false;
this.radCoffee.Checked = false;
}
// Clears all selections so that a new order
// can be placed. Resets the Order object back
// to its default values.
private void menuClearOrder_Click
(object sender, System.EventArgs e)
{
}
// Displays the values for the current instance of
// Order object members
private void menuPlaceOrder_Click(object sender,
System.EventArgs e)
{
}
// Event handler that gets raised when the Edit menu
// is clicked to change the special requests.
private void menuEditSpecial_Click(object sender,
System.EventArgs e)
{
}
// Event handler that gets raised when the Help
// menu is clicked to show the About message.
private void menuAbout_Click(object sender,
System.EventArgs e)
{
MessageBox.Show("Student Union -" +
" Diner by the Valley" +
"\n\n\nVersion 1.0");
}
// Event handler that gets raised when the
// Exit is clicked
private void menuExit_Click(object sender,
System.EventArgs e)
{
Application.Exit();
}
}
}
Order.cs:
using System;
using System.Windows.Forms;
namespace Diner
{
public class Order
{
public string[] menuEntree = new
string[] {"Chicken Salad",
"Ham and Cheese",
"Turkey",
"Vegetable Wrap",
"Tuna Salad",
"Avocado and Cheese",
"Club",
"Peanut Butter & Jelly",
"Cheese Toasty",
"Reuben"};
public decimal[] menuEntreePrice = new
decimal[] {4.50m,
5.00m,
4.75m,
4.00m,
4.50m,
4.00m,
5.50m,
3.75m,
3.50m,
5.00m};
private string entree;
private bool waterSelection;
private string drinkSelection;
private string specialRequest;
private decimal entreePrice;
private decimal drinkPrice;
// Default Constructor
public Order()
{
entree = "";
waterSelection = false;
specialRequest = "";
drinkPrice = 0;
entreePrice = 0;
}
//Property for Entree
public string Entree
{
get
{
return entree;
}
set
{
entree = value;
SetEntreePrice();
}
}
// Property for special request
public string SpecialRequest
{
get
{
return specialRequest;
}
set
{
specialRequest = value;
}
}
// Property for Water Selection
public bool WaterSelection
{
set
{
waterSelection = value;
}
}
// Property for Drink Selection
public string DrinkSelection
{
get
{
return drinkSelection;
}
set
{
drinkSelection = value;
SetDrinkPrice();
}
}
// Read-only property for entreee price
public decimal EntreePrice
{
get
{
return entreePrice;
}
}
// Read-only property for drink price
public decimal DrinkPrice
{
get
{
return drinkPrice;
}
}
// After the entree is set, store the entree price
public void SetEntreePrice()
{
for (int i = 0; i < menuEntree.Length; i++)
{
if (menuEntree[i] == entree)
{
entreePrice = menuEntreePrice[i];
}
}
}
// Return the water selection
public string GetWaterSelection()
{
string waterOrNot;
if (waterSelection)
{
waterOrNot = "Water";
}
else
{
waterOrNot = "No Water";
}
return waterOrNot;
}
// After the drink is set, store the drink price
public void SetDrinkPrice()
{
switch (drinkSelection)
{
case "Tea":
case "Coffee":
drinkPrice = 1.50m;
break;
case "Soda":
case "Lemonade":
drinkPrice = 2.00m;
break;
case "Milk":
case "Juice":
drinkPrice = 1.75m;
break;
}
}
// return the total cost of the order
public decimal DetermineTotalCharges()
{
return entreePrice + drinkPrice;
}
public override string ToString()
{
return "Toatal Due: " + DetermineTotalCharges().ToString("C");
}
}
}

DIsplaying a message in an exception

I wrote some code testing out a BankAccount and I finished it (for the most part).
The purpose was me attempting to learn how to throw and try/catch exceptions. For the most part I learned quite a bit. I realize this wasn't an "exceptional" case and if/else statements would have been more appropriate. I am just trying to learn exception handling.
I am trying to write the exception classes to extend a class to include a new message detailing the error being sent when an exception is thrown.
I read up on what a super class is, or base class in c#, and tried it. It compiles and looks right but I don't know what I am doing wrong. Can someone explain to me why my message in my throw new NegativeDepositException will not show.
What I would like for it to do, is to throw a message instead of me putting a string in MessageBox.Show.
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 WindowsFormsApplication2
{
public partial class Form1 : Form
{
public class NegativeBalanceException : Exception { }
public class NegativeWithdrawException : Exception { }
public class NegativeDepositException : Exception
{
public NegativeDepositException() { } // this doesn't do what I would like for it to do.
public NegativeDepositException(string message)
: base(message) { }
}
public Form1()
{
InitializeComponent();
}
public class BankAccount
{
decimal amount = 300.00m;
// Declare Delegate Type Object
public delegate void BankDelegate(decimal oldBalance, decimal newBalance);
// Create Delegate Type Events
public event BankDelegate OnDeposit;
public event BankDelegate OnWithdraw;
public void Deposit(decimal a)
{
if (a < 0)
throw new NegativeDepositException(); //"type some message here instead of messagebox below");
OnDeposit(this.amount, this.amount + a);
this.amount += a;
}
public void Withdraw(decimal a)
{
if (a < 0)
throw new NegativeWithdrawException();
OnWithdraw(this.amount, this.amount - a);
this.amount -= a;
if (this.amount < 0)
throw new NegativeBalanceException();
}
}
// this is my bank class variable...
BankAccount account = null;
private void Form1_Load(object sender, EventArgs e)
{
account = new BankAccount();
account.OnDeposit += new BankAccount.BankDelegate(account_OnDeposit);
account.OnWithdraw += new BankAccount.BankDelegate(account_OnWithdraw);
}
private void btnDeposit_Click(object sender, EventArgs e)
{
{
var amount = Convert.ToDecimal(textBox1.Text);
try { account.Deposit(amount); }
catch (NegativeDepositException)
{
MessageBox.Show("Cannot deposit negative amounts");
}
}
}
private void btnWIthdraw_Click(object sender, EventArgs e)
{
var amount = Convert.ToDecimal(textBox1.Text);
try { account.Withdraw(amount); }
catch (NegativeBalanceException)
{
MessageBox.Show("Cannot withdraw money that isn't there");
}
catch (NegativeWithdrawException)
{
MessageBox.Show("Cannot withdraw negative money");
}
}
void account_OnDeposit(decimal oldBalance, decimal newBalance)
{
label4.Text = oldBalance.ToString();
label5.Text = newBalance.ToString();
}
void account_OnWithdraw(decimal oldBalance, decimal newBalance)
{
label4.Text = oldBalance.ToString();
label5.Text = newBalance.ToString();
}
}
Maybe I'm misunderstanding the problem, but you're not passing the message when throwing the Exception;
It should be:
if (a < 0)
throw new NegativeDepositException("Cannot deposit negative amounts");
and when catching it you need to call the Message property of the Exception (which is in the Exception base class)
catch (NegativeWithdrawException exception)
{
MessageBox.Show(exception.Message);
}

Multiple events for one delegate

NOTE; Posting Pseudo Code Example... See Example Text below ( I told you this would be a hilarious mess ! )
Class Enter
{
public event EnterDelegate EnterDelegateEvent;
public event ExitDelegate ExitDelegateEvent;
public Enter(EventEventArgs e)
{
// do something
EnterOrder(e);
ExitEventArgs ev = new ExitEventArgs(string ticker, double prices.. etc);
ExitEvent(ev);
// update order status etc.
}
private double EnterOrder()
{
double ent = 0.00
if (EnterDelegateEvent != null)
{
ent = EnterDelegateEvent(this, e);
return ent;
}
else { return e.lo; }
}
public double ExitEvent(ExitEventArgs e)
{
// do something
ExitEvent(ev);
}
private double ExitEvent()
{
double ext = 0.00
if (ExitDelegateEvent != null)
{
ext = ExitDelegateEvent(this, e);
return ext;
}
else { return e.Hi; }
}
} // end Enter Class
Class EventHandlers
{
public double SendEnter(EventArgs e)
{
// send enter to order server here
return price;
}
public double SendExit(EventArgs e)
{
// send exit to order server here
return price
}
}
Orders Class
{
Enter ent = new Enter();
public GetOrders()
{
// get order data
// create order event
EnterEventArgs ev = new EnterEventArgs(ticker, price, data...etc);
ent.Enter(ev);
}
}
Orders.aspx.cs
{
EventHandlers evt = new EventHandlers();
Enter ent = new Enter();
Orders ord = new Orders();
Private void login()
{
// log into Orders Server
ent.EnterDelegateEvent += EnterDelegate(evt.SendEnter);
ent.ExitDelegateEvent += ExitDelegate(evt.SendExit);
}
private void logout()
{
// delete / remove delegate event handlers;
}
// initiate orders example event
private void btnclick_GetOrders()
{
ord.GetOrders();
}
}
In addition to running GetOrders, above, I also need to run another set of orders from GetBackTest().. This needs to be simultaneous at times so when it runs the EnterOrder() routine the EventDelegate needs to return if (EventDelegate == null) { return e.prices; }
Instead of using the EventHandler method...
Class Backtest
{
Enter ent = new Enter();
// kickoff enter order just as Orders Class does
// this class needs to NOT use the Event Delegate as Orders class does
}
Is there a straightforward way to turn the DelegateEvents on and off and make sure that only one of them is instantiated ?? IF I turn the Delegate events as Static, the the backtest class will use the eventhandler methods.
I'm not sure I completely understand the scenario you're describing, but events and delegates can be a little tricky at first. I would suggest reading up on some .NET event tutorials:
Events - http://msdn.microsoft.com/en-us/library/aa645739(VS.71).aspx
Delegates - http://msdn.microsoft.com/en-us/library/aa288459(VS.71).aspx
Another tutorial - http://www.csharp-station.com/Tutorials/lesson14.aspx
I would suggest working out a flow diagram first. It seems to me what exactly you want to do is not clear. Maybe with a flow diagram (or some other way of documenting what the system does) it would be.
I'm not even sure you need delegates for this problem the way you describe it.
I really didn't have to use event delegate however using other parameters to routes events required adding them and using them throughout or using existing and causing havoc, so to route the trade events using event delegates, I just added:
EventDelegateName += new DelegateName(eventhandler); // to top of orders.cs
EventDelegateName -= new DelegateName(eventhandler); // to bottom of orders.cs
so when backtest.cs ran the (Event == null) ran the alternate method.

TextBox not updating in C#

Specifically looking at the arrive method in the Customer class. I am using a for loop to create instances of the customer class, and when I try to write out their arrival times to a textBox (Just for testing purposes) the text box does not update. Why is this?
This is just a small simulation project for my Computing class. It is in its early stages, and is probably wrong in a lot of places!
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;
using System.Threading;
namespace QueueSimulation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("The form has loaded");
}
public void goButton_Click(object sender, EventArgs e)
{
Initialisers init = new Initialisers();
Customer customer = new Customer();
customer.Arrive();
}
private void stopButton_Click(object sender, EventArgs e)
{
// put code here to break out of the program
}
}
public class Customer : Initialisers
{
int waitingTime;
int arrivalTime;
int arrivalInterval;
Initialisers init = new Initialisers();
public void Arrive()
{
Customer[] customer = new Customer[1000];
int counter = 0;
for (int i = 1; i <= 10; i++)
{
customer[i] = new Customer();
customer[i].TimeArrived();
displayArrival.Text = displayArrival.Text + customer[i].TimeArrived().ToString();
// Implement something to either show the time in the queue if needed
Thread.Sleep(init.CustomerArriveTime*100);
}
MessageBox.Show("All of the customers have arrived");
}
public string TimeArrived()
{
return Convert.ToString(DateTime.Now);
}
public void Leave()
{
}
public void GetServed()
{
}
}
public class Server
{
bool servingStatus;
int servingTime;
public void Serve()
{
}
}
public class Initialisers : Form1
{
private int cust_no = 3;
public int CustomerArriveTime
{
get
{
return cust_no;
}
set
{
cust_no = value;
}
}
private int s_time = 4;
public int serveTime
{
get
{
return s_time;
}
set
{
s_time = value;
}
}
}
}
Pass to the Arrive the instance of the textbox object created on your Form1.
public void Arrive(TextBox displayArrival)
Why are you inheriting the Form1 in Initialiserz? It's better to pass the reference to Form1 instead of inheritance in this case.
This seems overly complex. Try to model the real world. What is Initialisers, and why do you have an inheritance tree: Customer > Initialisers > Form1?
You're customer is writing to its own TextBox, instead of the TextBox you're looking at (the one from the Form that is visible).
Why not have a method Arrive that sets a private field to DateTime.Now. Then, ask the Customer its TimeArrived, which returns this field. In your Form, call these methods as much as needed in your loop.
This also seperaties command (Arrive) from query (TimeArrived) + keeps your inheritance more logical.
You might not even need Initialisers anymore. And don't let Customer inherit from Form, because a Customer isn't a Form.
I think there is more of a design issue here, you are creating instances of customer inside customer.
Your customer Arrive method should probably be a function inside the another class, like below, customer should just define what a customer is. Processing them should be handled by a different class.
class Customer
{
int waitingTime;
int arrivalTime;
int arrivalInterval;
// etc...
}
class ProcessCustomers
{
pubic void Arrive()
{
// etc...
}
}
public void goButton_Click(object sender, EventArgs e)
{
Initialisers init = new Initialisers();
ProcessCustomers CustomerQueue = new ProcessCustomers();
CustomerQueue .Arrive();
}
But for the text box issue you will have to expose a property in the form class and set it like that,
string ArrivalTime
{
get
{
return textBox1.Text;
}
set
{
textBox1.Text = value;
}
}

Categories