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.
Related
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;
I am trying to carry the variables from the array over to the button click action. I can't find the way to set the scope to allow for this to work.
I have tried changing the modifiers to public, private, static, void, string, string[] etc.
I have also made all of the objects in the WinForms app set to Public
public partial class AutoPay : Form
{
public AutoPay()
{
InitializeComponent();
}
public void HeaderInformation(string dateAndTime, string fileNumber)
{
dateAndTime = DateTime.Now.ToString();
fileNumber = txtFileNumber.Text;
string[] headerArray = new string[2];
headerArray[0] = dateAndTime;
headerArray[1] = fileNumber;
}
public void BtnSave_Click(object sender, EventArgs e)
{
HeaderInformation(headerArray[0], headerArray[1]);
}
}
the headerArray[0] under the BtnSave_Click action has the red line under it showing that it is outside of the scope.
Try declaring the headerArray as a Property of the class
As was mentioned... you need to declare the headerArray outside the method... Also... it looks like you are trying to add information to the array before the array has information... try it this way(there are many other ways to do this too ;) ):
public partial class AutoPay : Form
{
private string[] headerArray; // <-- declare it here...
public AutoPay()
{
InitializeComponent();
headerArray = new string[2]; // <-- sometimes the normal way to initialize...
}
public void HeaderInformation(string dateAndTime, string fileNumber)
{
// reinitialize headerArray for safety....
headerArray = new string[2];
headerArray[0] = dateAndTime;
headerArray[1] = fileNumber;
}
public void BtnSave_Click(object sender, EventArgs e)
{
HeaderInformation(DateTime.Now.ToString(), txtFileNumber.Text);
}
}
or
public void HeaderInformation()
{
// reinitialize headerArray for safety....
headerArray = new string[2];
headerArray[0] = DateTime.Now.ToString();
headerArray[1] = txtFileNumber.Text;
}
public void BtnSave_Click(object sender, EventArgs e)
{
HeaderInformation();
}
This question already has answers here:
Stuck in function and booleans
(2 answers)
Closed 5 years ago.
//I have to create a program that determines if the name is written in the correct format, then once it deems it correct it separates the first and last name.
public partial class nameFormatForm : Form
{
public nameFormatForm()
{
InitializeComponent();
}
private bool IsValidFullName(string str)
{
bool letters;
bool character;
bool fullname;
foreach (char ch in str)
{
if (char.IsLetter(ch) && str.Contains(", "))
{
fullname = true;
}
else
{
MessageBox.Show("Full name is not in the proper format");
}
}
return fullname;
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void clearScreenButton_Click(object sender, EventArgs e)
{
exitButton.Focus();
displayFirstLabel.Text = "";
displayLastLabel.Text = "";
nameTextBox.Text = "";
}
private void formatNameButton_Click(object sender, EventArgs e)
{
clearScreenButton.Focus();
}
}
Always remember these 3 rules for C#:
To use a variable, it must be initialized.
Field members are initialized with a default value
Locals are NOT initialized with a default value.
You are breaking rule 1: Using fullname before it is initialized. The following program will clarify this:
public class Program
{
public static void Main()
{
// This is a local and NOT initialized
int number;
var person = new Person();
Console.WriteLine(person.age); // This will work
Console.WriteLine(number); // This will not work
Console.Read();
}
}
public class Person
{
// This is a field so it will be initialized to the default of int which is zero
public int age;
}
To fix your issue, you need to initialize fullname:
bool fullname = false;
I would rename the variable to a more readable name such as isFullName.
Declaring a variable with no initial value and then returning it in a method with an if statement that does not determine the value doesn't make any sense. You have to assign a value to fullname if you want to return its value.
Init this variable first:
bool fullname = false;
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());
}
All i want to do is pass a string from one void to another.
private void getFilename2()
{
if (textBox2.TextLength.Equals("0"))
{
}
else
{
string inputString = textBox2.Text.ToString();
string last = inputString.Substring(inputString.LastIndexOf('\\') + 1);
string[] filename2 = last.Split('.');
}
}
private void button1_Click(object sender, EventArgs e)
{
getFilename1();
getFilename2();
string filez = filename2;
}
I know this doesn't work but I'm very unfamiliar with how to move strings around in voids.
You should replace your getFilename2 function with
Path.GetFileNameWithoutExtension(textBox2.Text)
Your best bet would be to use a class field/property, or a function that returns a value.
string filez = GetFilename2();
private string GetFilename2() {
{
if (textBox2.TextLength.Equals("0")) return "";
string inputString = textBox2.Text.ToString();
string last = inputString.Substring(inputString.LastIndexOf('\\') + 1);
return last.Split('.');
}
You could pass the string by reference as a parameter to your functions
private void button1_Click(object sender, EventArgs e)
{
string fileName;
getFilename1(ref string fileName);
}
private void getFilename1(ref string fileName)
{
// Whatever you do with fileName here will be reflected in the other function
}
Let's start with the name of your method: getFilename2.
The prefix of "get" implies the method should have a return type
A more appropriate name may be SetFileName
I'm assuming there is a getFileName1 method that is retrieving the file name from textBox1 and has the exact same code as getFileName2, but uses textBox1 instead of textBox2. This would be a good place to refactor your code and create a common method that can be reused:
private string GetFileName(string str)
{
if (string.IsNullOrEmpty(str)) return string.Empty;
string last = str.Substring(str.LastIndexOf('\\') + 1);
return last.Split('.');
}
But, we can refactor again and just use a built-in .NET method:
private string GetFileName(string str)
{
return Path.GetFileNameWithoutExtension(str);
}
And now that there is a common method, we can re-use it as needed:
private void button1_Click(object sender, EventArgs e)
{
string filez = GetFileName(textBox2.Text);
}
Now we have a method of GetFileName(); all it is doing is calling a built-in .NET method of GetFileNameWithoutExtension(). So, instead of even having a method, we should just use the built-in .NET method for returning a file name:
private void button1_Click(object sender, EventArgs e)
{
string filez = Path.GetFileNameWithoutExtension(textBox2.Text);
}
Now, let's look at passing a string from one void to another. Typically, you'd want to do this with an internal field or property. Since I'm partial to properties, I'll use them as an example:
private string FileName1 {get; set;}
private string FileName2 {get; set;}
private void SetFileName1()
{
FileName1 = Path.GetFileNameWithoutExtension(textBox1.Text);
}
private void SetFileName2()
{
FileName2 = Path.GetFileNameWithoutExtension(textBox2.Text);
}
private void button1_Click(object sender, EventArgs e)
{
SetFileName1();
SetFileName2();
string filez1 = FileName1;
string filez2 = FileName2;
}
However, if you did not want to use internal fields or properties, you could set the values by ref as answered by Rachel
If you're passing strings around, ideally you should be explicitly passing them around. IE: make your functions take and/or return the values they'll work with, especially if the return values aren't intended to be used by anything but the code that calls getFilename2. If you can't do that, however, you can declare a private string filename1 = null; public string[] filename2 = null inside the class, but outside any of your methods.
If you go that route, make sure to remove any string filename1 or string[] filename2 from your methods, or you'll end up declaring a local variable with the same name (and never setting the instance variables).
You can store it in a class level variable. In that way it can be accessed by any function.