How to change my global variable in other function? c# - c#

I want to change the global integer- amount, by make his value as 'c' value, how can i do that?
public static class Globals
{
public const int amount = 5689;
}
private void button1_Click(object sender, EventArgs e)
{
int b = int.Parse(textBox2.Text);
int c = Globals.amount - b;
textBox3.Text = c.ToString();
**Globals.amount = c;** // ***how do i set this?***
}

Since amount is defined as a constant, you can't change it.
You can, however change it if you made it a non-constant static variable instead.
public static int amount = 5689;

Related

The error is "Error CS0106 The modifier 'readonly' is not valid for this item "

namespace Practice
{
public class LargestPrimeFactor {
public static void main(String[] args) {
readonly long NUM = 600851475143L;
int i;
int n;
int flag = 0;
long primeFactor = 1;
long factor = 1;
for(i=2; i<NUM/2; i++) {
flag = 0;
for(n=2; n < i/2; n++) {
if(i % n == 0) {
flag = 1;
}
}
if(flag == 0){
factor = i;
if(NUM % factor == 0) {
primeFactor = factor;
Console.WriteLine("factor = " + factor);
}
}
}
Console.WriteLine(primeFactor);
}
}
}
Please explain what I’m doing wrong. I don’t know how to declare this variable so that it is read-only. When I put it outside of the method, I get different errors.
The readonly modifier is valid at the class level, so you could refactor it as:
public class LargestPrimeFactor {
readonly long NUM = 600851475143L;
public static void main(String[] args) {
// ...
}
}
Alternatively, you can use the const keyword either at the field level or inside a method:
public class LargestPrimeFactor {
const long NUM = 600851475143L;
public static void main(String[] args) {
// ...
}
}
or
public class LargestPrimeFactor {
public static void main(String[] args) {
const long NUM = 600851475143L;
// ...
}
}
readonly is most useful for variables that will be fully initialized before the constructor completes but don't have a constant representation, e.g.
readonly DateTime startedAt = DateTime.Now;
You want to declare NUM as a const instead of a readonly.
If you read the documentation for readonly, you'll see that it doesn't apply to variables declared inside a method. The keyword can only be applied to:
readonly field declarations
readonly struct definitions
readonly instance members
ref readonly method return
If you want a variable that's defined inside a method to not be modified, you can declare it with the const keyword:
public static void Main(string[] args)
{
const long num = 600851475143L;
}
I wanted to do something similar, but for a value that was calculated at runtime. Instead of const long NUM = 600851475143L I used the new(ish) local function feature - not exactly const or readonly, but a way to lock down a value
long NUM() => someLongRuntimeValue;
. . .
for(i=2; i<NUM()/2; i++) {
. . .
This costs of a couple parentheses and a bit of runtime overhead - in my case the value was going to be used only a few times. It was a defensive code practice in a module edited by many people, a way of saying "I know you might think you want to change this value, but if you do you will break things" - my future self being one of the people I'm talking to.

How access a variable in class which that variable defined in the form

For example I have a button that get me 3 variable:
private void Savebtn_Click(object sender, EventArgs e)
{
int A, B, C;
A = int.Parse(textBox1.Text);
B = int.Parse(textBox2.Text);
C = int.Parse(textBox3.Text);
}
and I have class that use these variable to compute another variable for example:
class Class1
{
public static int MWCompute()
{
int MW;
MW = A * B * C;
return MW;
}
}
And again I want to use this MW variable in my form for example:
if (something)
{
textbox4.text = MW.ToString();
}
Without declaring A, B, C as static variables, you can call MWCompute by passing those variables as parameters and get the result in a local variable MW. Then, you can apply your logic in the if statement:
private void Savebtn_Click(object sender, EventArgs e)
{
int A, B, C;
A = int.Parse(textBox1.Text);
B = int.Parse(textBox2.Text);
C = int.Parse(textBox3.Text);
int MW = Class1.MWCompute(A, B, C);
if (something)
{
textbox4.text = MW.ToString();
}
}
And Class1 defined as:
class Class1 // as suggested by #Jamiec: give this class a meaningful name
{
public static int MWCompute(int A, int B, int C)
{
int MW;
MW = A * B * C;
return MW;
}
}
You typically do this by passing parameters to the class, either in the constructor or in the method itself, as appropriate.
class MWCalculator // give it a meaningful name, for starters!
{
public static int MWCompute(int A, int B, int C)
{
int MW;
MW = A * B * C;
return MW;
}
}
Then in your form:
private void Savebtn_Click(object sender, EventArgs e)
{
int A, B, C;
A = int.Parse(textBox1.Text);
B = int.Parse(textBox2.Text);
C = int.Parse(textBox3.Text);
var calc = new MwCalculator();
textBox4.Text = calc.MWCompute(A,B,C).ToString();
}
You have two problems related to the scope:
You can't access non-static variables from a static method without the class instance;
You can't access method variables from another method.
The solution would be to move A, B and C outside the method and into the class, and make your MWCompute method non-static.

how i can send two or more than two arguments to private methods of class using properties

hi i have class with one private method. i am trying to send two values(two arguments) to its method using property but its not working.some time it gives compiler error and some time wrong answer(logical error).
class sum
{
private int add (int a, int b)
{
return a+b;
}
private int ts;
public int MyProperty
{
get { return ts; }
set { ts = add(value,value);
}
}
Code in main Class
private void button5_Click(object sender, EventArgs e)
{
sum sumv = new sum();
sumv.MyProperty=2;
int sumj = sumv.MyProperty;
MessageBox.Show(sumj.ToString());
}
Well the short answer is: you can't send two parameters to a property setter.
Properties are just meant to be synthaxical sugar to avoid having to implement java/c++-like accessors (getProperty(), setProperty()...).
That being said, you can totally do some work on the value you get in the property's setter (like checking if it is in a certain range of values, or even modifying it...). But value is the only value you will ever get by using it.
And public methods aren't inherently bad, else we wouldn't have the mean to use them in the first place. I'd like to know where you've seen that.
If you want to practice in OOP concepts - your way isn't correct.
This class much better suitable for OOP:
public class Adder
{
public int Result {get; private set;} // private setter allow you to hide this member.
public void Sum(int value1, int value2)
{
Result = value1 + value2;
}
}
There seems to be a lot of confusion here caused by OOP principles. Here's a couple of ways you could achieve what you want.
Make your method public. There's nothing wrong with doing this as you are not storing anything and there's nothing to encapsulate:
public class Adder
{
public int Add(int value1, int value2)
{
return value1 + value2;
}
}
Pass in your parameters in the class constructor:
public class Adder
{
private int _value1;
private int _value2;
public Adder(int value1, int value1)
{
_value1 = value1;
_value3 = value2;
}
public int Add()
{
return _value1 + _value2;
}
}
There is a rule of some sort about this :
If you have private method that you want to expose to other classes
but you don't want to make it public then create a public delegate
and pass your method with this delegate
Your property can be of delegate type. In this case the get method will return delegate. This delegates contains your method add, that you can run :
class sum
{
private int add (int a, int b)
{
return a+b;
}
public Func<int, int, int> MyProperty
{
get { return add; }
}
}
And use it like this :
private void button5_Click(object sender, EventArgs e)
{
sum sumv = new sum();
int sumj = sumv.MyProperty(5, 10);
MessageBox.Show(sumj.ToString());
}

Variable not being seen in C# code

Learning C# and hit a snag.
Why isn't the variable 'number' used here?
public partial class Form1 : Form
{
static string labelText = "";
static string number = "";
public Form1()
{
InitializeComponent();
}
private void serialNumber_TextChanged(object sender, EventArgs e)
{
string number = this.serialNumber.Text;
}
I keep getting a warning that field 'number' is assigned but not used.
string number = this.serialNumber.Text; this line creates a new string.
try this to avoid the warning
public partial class Form1 : Form
{
static string labelText = "";
static string number = "";
public Form1()
{
InitializeComponent();
}
private void serialNumber_TextChanged(object sender, EventArgs e)
{
number = this.serialNumber.Text;
}
string number declares a new local variable which hides the static member variable.
Change these lines:
static string number = "";
private void serialNumber_TextChanged(object sender, EventArgs e)
{
string number = this.serialNumber.Text;
}
to
private string number = "";
private void serialNumber_TextChanged(object sender, EventArgs e)
{
number = this.serialNumber.Text;
}
In your serialNumber_TextChanged method you declare a local variable called number. So if that is your complete code you never actually assign anything to Form1.number apart of the static initialization.
That's exactly what's happening: you are assigning a value to the variable number, and then you don't do anything with that variable.
First off, the warning is valid, and relates to the static member, which, in fact, is assigned and never used. The one in serialNumber_TextChanged is local to that method and by definition, different.
This: "Why isn't the variable 'number' used here?"...I do not understand.
It happens because of the string in the instruction string number = this.serialNumber.Text;, which is declaring a new variable, different from the class field, despite having the same name. Remove the string modifier and the instruction will refer to the class field already declared.

Calculate in C#

Hello everyone I am trying to make since of what I am doing wrong or maybe I am over thinking it again. I am trying to create a class and in the class I am calling 2 private variables such as num1 and num2. Then i create a public property that corresponds to num 1 and num2. Then after I create that I need to create a public overriable method called calculate and this will add the two variables together and returns the results. Then I have a add button that I have to add the code to the button that adds the two numbers and output the result to a messagebox.I have tried a couple different ways and I still am not getting it.
Here is code 1:
public abstract class CalulateValues
{
protected List<int> values = new List<int>();
public void AddValue(int value) { values.Add(value); }
public abstract int Calculate();
}
public class Add : CalulateValues
{
public override int Calculate()
{
return values.Sum(x => x);
}
}
and here is code 2 I tried:
class CalculateValues
{
private int _num1;
private int _num2;
public int Num1
{
get
{
return _num1;
}
set
{
_num1 = value;
}
}
public int Num2
{
get
{
return _num2;
}
set
{
_num2 = value;
}
}
public virtual int calculate()
{
return _num1 + _num2;
}
}
Now when it comes with the button I have tried this code:
public partial class Form2 : Form
{
public Form2()
{
CalculateValues myAdd = new CalculateValues();
MulitplyValues Add = new MulitplyValues();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int total = myAdd.Add(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
MessageBox.Show(total.ToString());
}
I am not too sure what I am doing wrong maybe I am not laying out the code the right way.
You have declared myAdd as a local variable in the Form2 constructor. Declare it as a global variable in order to be able to call it from button1_Click()
In addition to this, are you getting any error or exception? Second, where did you declare Add method that accepts two parameters?
public partial class Form2 : Form
{
CalculateValues myAdd;
public Form2()
{
InitializeComponent();
myAdd = new CalculateValues();
}
private void button1_Click(object sender, EventArgs e)
{
int total = myAdd.Add(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
MessageBox.Show(total.ToString());
}
}
And then go and look up firstly a C# tutorial, then look at detail on variable scope.
int total = myAdd.Add(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
myAdd has no Add method at all. It is AddValue. And you should call Calculate and retrieve the result.
Declare myAdd as member variable instead local in constructor.
And try that:
myAdd.AddValue(int.Parse(textBox1.Text)
myAdd.AddValue(int.Parse(textBox2.Text);
int total = myAdd.Calculate();
MessageBox.Show(total.ToString());
Multiple bugs in your code.
You don't have a method Add, you shoudl use the method calculate like this
private void button1_Click(object sender, EventArgs e)
{
int total = myAdd.Add(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
MessageBox.Show(total.ToString());
}
You need to declare the myAdd variable outside of the constructor, even if you only initialize in the Form2() constructor.
Your CalculateValues class does not have an "Add" method.
Instead you should be calling the "Calculate" method like this:
public partial class Form2 : Form
{
public Form2()
{
CalculateValues myAdd = new CalculateValues();
MulitplyValues Add = new MulitplyValues();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int total = myAdd.Calculate(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
MessageBox.Show(total.ToString());
}

Categories