Trying to use a numericupdown not in a void - c#

I am trying to make an integer = numericupdown not within a method. What I am trying to say is I want to initialize an integer that can be used every where in the main form.
int number1 = Convert.ToInt32(numericUpDown1.Value);
I want to define it before I call any events so I can use it everywhere. Thanks

Create a static class and set your property number1 to a static property.
public static class KeySets
{
public static int Number1 { get; set; }
}
then set property
KeySets.Number1 = Convert.ToInt32(numericUpDown1.Value);
then you can use it every where.

I see at least 2 options:
1: declare it as a field and initialize in constructor after InitializeCompoenent()
int number1;
public MyForm()
{
InitializeComponent();
number1 = Convert.ToInt32(numericUpDown1.Value);
}
2: Create a property returning what you want
int number1
{
get { return Convert.ToInt32(numericUpDown1.Value); }
}

Related

How can I write a single constructor method to set two fields to a specific value

I am learning about writing constructors and properties in c# and was asked to write a console app and class to operate a beverage machine. I wrote part of the class code but ran into an issue. One of the many blocks of code asks for a constructor method that starts the SodaCanCount at 5 bottles and sets the CustBalance field to zero. I don't know what this constructor should look like. I am specifically talking about the private sodaVandorClass(), right under the two private fields.
I wrote what I could so far and I have no errors however the SodaVendorClass does not look right.
namespace VendorClass
{
public class SodaVendorClass
{
// members
// fields
//Customer balance is $0 until the customer inserts a dollar
//All customer entries are one dollar increments and a soda costs one dollar.
private int CustBalance = 0;
//a machine holds 10 cans of soda
private int SodaCanCount = 5;
//A soda costs 1 dollar
//private int sodaCost = 1;
public int _SodaCanCount
{
get
{
return SodaCanCount;
}
}
public int _CustBalance
{
get
{
return CustBalance;
}
}
public int BuySoda(int pCustBalance, int SodaCanCount)
{
return SodaCanCount;
}
public void AcceptCash(int CustBalance)
{
CustBalance++;
}
public int GiveRefund(int pCustBalance)
{
return CustBalance;
}
}
I only want to see an example of a constructor that sets default values for my private class fields. Any help will be appreciated.
You can define a public constructor like below but probably you don't need one if you enable your properties to set values too
public SodaVendorClass()
{
this.CustBalance = 0;
this.SodaCanCount = 0;
}
You can make your properties writable too. Notice below are auto properties and in such case you don't need those private backing fields explicitly.
public int SodaCanCount
{
get; set;
}
public int CustBalance
{
get; set;
}
You can instantiate your type saying (using Object Initializer construct)
SodaVendorClass sc = new SodaVendorClass
{
SodaCanCount = 10,
CustBalance = 500,
};
A constructor for this class could look like this:
public SodaVendorClass () {
}
That would be an empty constructor that does nothing.
To set the two values you want, you can add some paramters:
public SodaVendorClass (int customerBalance, int sodaCount) {
this.CustBalance = customerBalance;
this.SodaCanCount = sodaCount;
}
To create an instance of this class with 5 soda cans and a customer balance of 0, you would call the constructor in the code like this:
var vendor = new SodaVendorClass(0, 5);
namespace VendorClass
{
public class SodaVendorClass
{
private int CustBalance;
private int SodaCanCount;
//...
public SodaVendorClass() // default constuctor
{
CustBalance = 0;
SodaCanCount = 5;
}
//...
}
}
Default constructor is called when you are creating object like this:
SodaVendorClass obj = new SodaVendorClass();
So obj._SodaCanCount is 5 and obj._CustBalance is 0
Also you can define constructor with parameters.
public SodaVendorClass(int balance, int count)
{
CustBalance = balance;
SodaCanCount = count;
}
and create call this constructor.
SodaVendorClass obj = new SodaVendorClass(0, 5);
A constructor is being used while creating a object like "Class obj=new Calss()". If you don define a constructor in your class a default constructor will be provided implicitly.User defined Constructor usually used for initializing value for class properties. Unlike function constructor does not have any return type at all not even void. All the answers are good.
public class SodaVendorClass{
private int CustBalance = 0;
//a machine holds 10 cans of soda
private int SodaCanCount = 5;
//A soda costs 1 dollar
//private int sodaCost = 1;
public int _SodaCanCount
{
get
{
return SodaCanCount;
}
}
public int _CustBalance
{
get
{
return CustBalance;
}
}
public SodaVendorClass(int cancount, int sodacost){
SodaCanCount=cancount;
sodaCost=sodacost;
}
}
//creating a object of Sodavendorclass
Sodavendorclass obj=new Sodavendorclass(0,0); //Provided value for class property
Notice that at the time of object creation, provided for Property. This is one of the way you can use constructor.

Static variable is not initialized immediately

public class variables {
public static int edit{ get;set; }
}
And also tried:
public static int edit = 0;
public static int edit { get; set; }
public static int edits { get { return edit; } }
Using the form
form:form1 {
// Changing the value of variable to 1
private void Form1_Load(object sender, EventArgs e) {
variables.edit=1;
}
// Calling the new form where I'll use its value
private void Button_Click(object sender, EventArgs e){
form2 A=new form2();
A.Show();
}
}
form:form2{
// Showing the value of the variable in a message box
private void Form2_Load(object sender, EventArgs e){
MessageBox.show(variables.edit.ToSting());
}
}
The Message in all cases returned 0 least that call again. I need to know how to make the values initialize step as the first. I have to tab Use the many variable that keep data from one form to another and use in the load.
Make sure your class variables is static, not only the fields/properties:
public static class variables {
public static int edit = 0;
}
Another source of problem with static classes is when you use one field/property when setting another:
public static class variables {
public static int someValue = 2;
public static int other = someValue + 3;
}
AFAIK, you can't be sure of what field/property will be set first by the static constructor at runtime, unless you set the values in the static constructor, like this:
public static class variables {
static variables() {
someValue = 0;
other = someValue + 3;
}
public static int someValue;
public static int other;
}
If you are declaring static fields/properties in a really non-static class, check for the problem above, and if nothing else is changing the static field/property in another place, even inside the non-static class.

Automatic properties

I want to know that when you create an Automatic property
and invoke the set in the main() method for a random value , where is that value being stored ?as in this example :
class Program
{
static void Main(string[] args)
{
Example W = new Example();
W.Num = 10;
Console.WriteLine("{0}", W.Num);
Console.WriteLine("{0}", W.getNum());
}
}
class Example
{
private int num;
public int Num { get; set; }
public int getNum() { return num; }
}
why is the output :
100
Because you are returning num, not Num. And num was not initialized, so this value is 0.
Auto-implemented properties makes code cleaner when no additional logic is required for the getter or setter. The compiler actually generates a backing field for the auto-implemented property, but this backing field is not visible from your code.
In your example there is no connection between the num field and the Num property, so there no reason why the num should change.
This is nothing abnormal here.
When you call
Example W = new Example();
then initially num = 0 and Num = 0;
you assigned Num, not num.
num in your Example class is redundant.
If you wrote this before automatic property initialisers were added to c#, it would look like this:
private int num;
public int Num
{
get{ return num;}
set{ num = value;}
}
Writing public public int Num { get; set; } is essentially the same thing behind the scenes. There is no need to implement getNum() (like Java), since this is equivalent to int a = w.Num;.
if use new keyword , you created new instance your class And all object recreated.
For Example ;
class Program
{
static void Main(string[] args)
{
Example W = new Example();
W.Num = 10;
Example W1 = new Example();
Console.WriteLine("{0}", W.Num); //10
Console.WriteLine("{0}", W1.Num); //0
}
}
this is only information your answer ; you returning different variable. you not set them.

C# help. Call operations from classes

class Addition : Form1
{
public string AdditionTotal(){
string AdditionTotal;
int num1 = int.Parse(txtFirstNumber.Text);
int num2 = int.Parse(txtSecondNumber.Text);
AdditionTotal = (num1 + num2).ToString();
return AdditionTotal;
}
public AdditionEqual() //Throws an error here
{
Convert.ToInt32(AdditionTotal);
int AdditionEqual = AdditionTotal;
Addition frm2 = new Addition();
frm2.Show();
this.Hide();
Form 1:
public Form1()
{
InitializeComponent();
}
public string AdditionEqual { get; set; }
private void button1_Click(object sender, EventArgs e)
{
Addition MyLaptop = new Addition();
if (Add.Checked)
{
MessageBox.Show( this.AdditionEqual);
}
Can someone please edit and tell me whats wrong with my code here? I need to use classes and radiobuttons to make a calculator. There's currently 1 error. It says the public AdditionEqual() needs to have a return type. Theres only 1 error but I dont know if the code will actually work after that's fixed. Can someone help?
The function needs a return type. Your first method returns a string:
public string AdditionTotal(){
That string is indicating what datatype the function will return.
public AdditionEqual()
This function doesn't have that indicator. If you don't intend for the method to return anything, use void.
public void AdditionEqual()

Trying to add with method, believe something is not instantiating

When I type in the textbox, I am wanting it to add the numbers, instead if I type (for example) 12, and click deposit again, it only shows 12. I think this is because it seems to think thats its 0 plus 12 everytime. Something doesnt seem to be instantiating correctly. I think. Can anyone point out what I am doing incorrectly?
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_deposit_Click(object sender, EventArgs e)
{
double input;
input = double.Parse((putin.Text));
BankAccount a = new BankAccount(input);
aMtBox.Text = a.AccountBalance.ToString();
}
}
public class BankAccount
{
private double num1;
private double accountBalance;
public BankAccount(double input)
{
num1 = input;
Deposit();
}
public double Num1
{
set {num1 = value;}
get {return num1;}}
public double AccountBalance
{
get {return accountBalance;}
set {accountBalance = value;}}
public void Deposit()
{
accountBalance = accountBalance + num1;
}
}
}
You're creating a new instance of BankAccount each time the button is clicked - so accountBalance will be 0.0 (the default value for a field of type double). How did you expect it to "know" about the previous balance?
It's entirely possible that you should have an instance variable of type BankAccount in your form. You should also consider what the num1 instance variable in BankAccount is meant to represent. The name certainly doesn't tell us anything. It feels like it should actually just be a parameter to the Deposit method.
Additionally, for currency values you should never use double - use either decimal, or an integer type to represent the number of cents (or pence, or whatever). You don't want to get into the normal binary floating point issue.
At this point, your method would become something like:
// I hate the VS-generated event names, but...
private void btn_deposit_Click(object sender, EventArgs e)
{
// TODO: Use decimal.TryParse, and handle invalid input cleanly.
decimal newDeposit = decimal.Parse(putin.Text);
account.Deposit(newDeposit);
aMtBox.Text = account.AccountBalance.ToString();
}
You need to have a BankAccount field for the form which is initialized with the form. Should look something like this:
public partial class Form1 : Form
{
private BankAccount account;
public Form1()
{
InitializeComponent();
account = new BankAccount(0);
}
private void btn_Deposit_Click(object sender, EventArgs e)
{
account.Num1 = double.Parse((putin.Text));
account.Deposit();
aMtBox.Text = account.AccountBalance.ToString();
}
}
On a side note, Input should be validated, and the BankAccount class refactored to something like:
class BankAccount
{
private double num1;
private double accountBalance;
public BankAccount(double startingBalance)
{
accountBalance = startingBalance;
}
public double AccountBalance
{
get {return accountBalance;}
set {accountBalance = value;}
}
public void Deposit(double depositAmount)
{
accountBalance += depositAmount;
}
}

Categories

Resources