Im working a project in C# Visual Studio 2019
If i try to use i get this error:
Error CS0103 The name 'x' does not exist in the current context
Error CS0103 The name 'y' does not exist in the current context
How can i use variables normaly?
{
public Game()
{
InitializeComponent();
}
private void Game_Load(object sender, EventArgs e)
{
int x = 10;
int y = 11;
}
private void Lapkérés_Click(object sender, EventArgs e)
{
if (x > y)
{
MessageBox.Show("x bigger");
}
}
}
Because x and y are declared in a method, so they are termed local in the Game_Load Method. that means this two-variable exists in this Method and you can use those variables the entire Method's scope and the nested code blocks inside the method, but they won't exist after the method’s execution is over (in this case after the execution of Game_Load). so they won't be accessible from anywhere else.
Otherwise, if you want the variables to be used for the entire class, you should declare them out of a method and at the class-level. like this :
class Test
{
int x;
int y;
private void TestMethod()
{
x = 10;
y = 11;
}
}
so the variables will be available for all non-static methods declared in the class.
Because they don't exist in that context. The variables are defined, and thus exist, only in the Game_Load method.
It sounds like you want them to be class-level members instead:
class Game
{
private int x;
private int y;
public Game()
{
InitializeComponent();
}
private void Game_Load(object sender, EventArgs e)
{
this.x = 10;
this.y = 11;
}
private void Lapkérés_Click(object sender, EventArgs e)
{
if (this.x > this.y)
{
MessageBox.Show("x bigger");
}
}
}
In this way they will be created when the instance of the class is created and will survive within that instance. Any method in the class can access its instance's values for those variables.
Note that multiple instances of the Game class would each have their own values in those variables. Other scopes exist which may be relevant in other cases. For example, the values could be static or you may store them externally in a file or database to persist outside the running application, etc.
(For this particular, likely contrived example you don't even really need Game_Load, you can just set the values directly at the class-level when declaring them or in the Game() constructor. But I'll assume the plan here is to introduce more logic in Game_Load which otherwise wouldn't belong at the class level or in the constructor.)
For your variables to be accessible, they must be initiated.
Here they are in a private function which must be called this function before making your if condition
you have made x and y local variables for the Game_Load function.
You will need to move them to instance variables by declaring them at the class level, rather than the method level.
Define the variables at class level
{
private int x;
private int y;
public Game()
{
InitializeComponent();
}
private void Game_Load(object sender, EventArgs e)
{
x = 10;
y = 11;
}
private void Lapkérés_Click(object sender, EventArgs e)
{
if (x > y)
{
MessageBox.Show("x bigger");
}
}
}
You need to declare your variables (x and y) as private variables in your class but outside the function.
Here, you only declare x and y in the Game_Load function.
Also, don't use 'é' in your function name it won't work.
I think that the answers here answer everything, but I would like to clarify some things. The variables that you in the Game_Load method are only seen by the method. They cannot be accesed anywhere else. In order to be able to use them everywhere in your class, you have to declare these two variables in the class outside of any methods:
class SomeClass{
private int x; //can be accesed anywhere in the class
private int y; // can also be accesed anywhere in the class
public Game()
{
InitializeComponent();
}
private void Game_Load(object sender, EventArgs e)
{
x = 10;
y = 11;
}
private void Lapkérés_Click(object sender, EventArgs e)
{
if (x > y)
{
MessageBox.Show("x bigger");
}
}
}
When you declare your variables as private, they can be accesed anywhere in the class. Just make sure that you do not declare these variables in your methods.
Related
namespace LCB.Code
{
public class cuentaBanco
{
string nombre;
float cuenta;
public cuentaBanco(string nombre, float cuenta)
{
this.nombre = nombre;
this.cuenta = cuenta;
}
public void agregar(float incrementar)
{
this.cuenta += incrementar;
}
public void remover(float remover)
{
if (remover >this.cuenta)
{
this.cuenta = 0;
}
else
{
this.cuenta -= remover;
}
}
}
}
using LCB.Code;
namespace ACB
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = cuentaBanco.agregar(float.Parse(textBox1.Text)).ToString();
}
}
}
An instance of an object is required this means that you cannot call a NON STATIC method of a class without having declared and initialized an instance of that class. So you have two options. Make the agregar method static or initialize an instance of the cuentaBanco class. I really suggest to stay away from static methods unless you have a clear reason to condivide the method between many instances of your class and in your code I can't see any reason to have a static method. So I am going for the other option.
Make an instance of the cuentaBanco class...
private void button1_Click(object sender, EventArgs e)
{
cuentaBanco cuenta = new cuentaBanco("ABC", 0f);
label1.Text = cuenta.agregar(float.Parse(textBox1.Text)).ToString();
}
but now we have another problem. The agregar method is declared as void. It means that it doesn't return anything. So you can't apply a ToString() to a void returning method.
You need also change the agregar method to return the calculated value
public class cuentaBanco
{
....
public float agregar(float incrementar)
{
this.cuenta += incrementar;
return this.cuenta;
}
....
}
Again, looking at your class it seems that you want to have an object that keeps your counting and increment the internal number for every click on your button. In this case you want to keep a global object for your counting and declare and initialize a class level variable of type cuentaBanco at the initialization of your form. Now you can use that variable to make your countings
public partial class Form1 : Form
{
private cuentaBanco cuenta;
public Form1()
{
InitializeComponent();
cuenta = new cuentaBanco("ABC", 0f);
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = cuenta.agregar(float.Parse(textBox1.Text)).ToString();
}
}
You should make method agregar static.
Also after making agregar static you should make cuenta static too. Also the agregar method is void you can't set it to label1.Text you should change it's return type yo float:
static float _cuenta;
public static float agregar(float incrementar)
{
_cuenta += incrementar;
return _cuenta;
}
Also in the cuentaBanco method remove the this keyword and set a valid name instead of cuenta like _cuenta:
public cuentaBanco(string nombre, float cuenta)
{
this.nombre = nombre;
_cuenta = cuenta;
}
I am little confused with constructor use so can someone please explain me on simple example. I give example of a simple code and in it I don't know why to use constructor instead of the way I am using.
I made class for calculation
public class Calculation
{
private double a;
private double b;
private double c;
private double d;
private double e;
public Calculation ()
{
}
public double e (double a,double b,double c,double d)
{
e = (a * 10) / (b * c * d);
return e;
}
}
Now I made an instance of this class in my windows form
public partial class Form1 : Form
{
public Calculation example;
public Form1()
{
InitializeComponent();
example = new Calculation();
}
private double A = 200;
private double B = 45;
private double C = 55;
private double D = 20;
private void button1_Click(object sender, EventArgs e)
{
string E = (example.e(A, B, C, D).ToString());
label1.Text = E;
}
Whats are the advantages and disadvantages of this method that I used? Is there more efficient way to do this with the constructor?
I am confused because everything is public either way, you can't instantiate private class and private constructor.
You would want to use a constructor with parameters instead of a method with parameters when you want to create an instance of your class and at the same time set its internal state.
Constructors have the task of initializing the object's data members and leaving the resulting object in a valid state.
You should learn more about concepts of OOP (object-oriented programming). Start by reading about Methods, Classes, Constructors, Setters and Getters to learn the basics then go from there.
I have a simple asp.net webform page which i use to display page related data based on pageID.
I am trying to define page level variable so that i can access there variable in different function used in this page. But i am getting few error. for example if my code is like
public partial class PageHome : System.Web.UI.Page
{
int _LangID = 1;
_LangID = int.Parse(Helper.GetAppSetting("LangID_En"));
int _PageID = 0;
int _PID = Helper.GetPageID(_LangID, "Home.aspx");
protected void Page_Load(object sender, EventArgs e)
{
int _LanguageID = _LangID;
GetPageDetails(_PageID);
}
}
Then i get
Error message:
Invalid token '=' in class, struct, or interface member declaration (_LangID = int.Parse(Helper.GetAppSetting("LangID_En"));)
Invalid token '.' in class, struct, or interface member declaration (_LangID = int.Parse(Helper.GetAppSetting("LangID_En"));)
Method must have a return type
Identifier expected
and if i try to use define these variable inside constructor
//public PageHome()
//{
//int _LangID = 1;
//_LangID = int.Parse(Helper.GetAppSetting("LangID_En"));
//int _PageID = 0;
//int _PID = Helper.GetPageID(_LangID, "Home.aspx");
//}
Then I get different errors like
The name '_LangID' does not exist in the current context
The name '_PageID ' does not exist in the current context
What is the best way to define page level variable which are defined once and access in different function
Update:
Helper.GetAppSetting("LangID_En") and Helper.GetPageID(_LangID, "Home.aspx") functions are defined in a seperate class file under kept under App_Code/Helper/Helper.cs
Update Two: Working code based on JonSKeet answer.
public partial class PageHome : System.Web.UI.Page
{
int _LangID = 1;
_LangID = int.Parse(Helper.GetAppSetting("LangID_En"));
int _PageID = 0;
public PageHome()
{
int _PID = Helper.GetPageID(_LangID, "Home.aspx");
}
protected void Page_Load(object sender, EventArgs e)
{
int _LanguageID = _LangID;
GetPageDetails(_PageID);
}
}
You can't just have a statement like:
_LangID = int.Parse(Helper.GetAppSetting("LangID_En"));
within a class declaration. It would have to be in a method, or constructor, or something like that.
However, given that you've just declared the variable, you could simply change these two lines:
int _LangID = 1;
_LangID = int.Parse(Helper.GetAppSetting("LangID_En"));
... to one:
int _LangID = int.Parse(Helper.GetAppSetting("LangID_En"));
However, you'll then have an error here:
int _PID = Helper.GetPageID(_LangID, "Home.aspx");
as you can't refer to one instance field within the initializer for another. That initialization would have to happen in the constructor... in which case I'd suggest doing both of them in the constructor, for clarity:
public class PageHome : Page
{
// Do you really not need to initialize this to something else?
int _PageID = 0;
int _LangID;
int _PID;
public PageHome()
{
_LangID = int.Parse(Helper.GetAppSetting("LangID_En"));
_PID = Helper.GetPageID(_LangID, "Home.aspx");
}
...
}
On the other hand, do those values actually change on a per-page-instance basis? Perhaps they should actually be static fields? (It's hard to tell what the bigger picture is here.)
Just to make sure i would sugest tryparsing the int from the appsettings
You could make some sort of tryparse methode in witch you can get the appsettings. This way there wont be an error if the settings are missing and the int will have a null value.
protected void Page_Load(object sender, EventArgs e)
{
int? _LangID = TryParse2(Helper.GetAppSetting("LangID_En"));
}
int? TryParse2(string s) {
int i;
if (!int.TryParse(s, out i)) {
return null;
} else {
return i;
}
}
Also does your class helper get the app settings the corect way? I personaly use somthing like
var debugSetting = ConfigurationManager.AppSettings["IsDebug"];
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());
}
I don't understand why inheriting from EventArgs is useful.
public class ClickedEventArgs : EventArgs
{
int x;
int y;
public ClickedEventArgs (int x, int y)
{
this.x = x;
this.y = y;
}
public int X { get { return x; } }
public int Y { get { return y; } }
}
In the code above, how can I use this inheritance?
I also want to learn how I can call this code block from default.aspx
Are you asking why it's useful to derive from EventArgs in the first place? I have to say that with C# 1 it didn't make a lot of sense, because of the way delegate conversion worked - but as of C# 2 it's more sensible. It allows an event handler to be registered with an event even if it doesn't care about the details of the event arguments.
For example:
void LogEvent(object sender, EventArgs e)
{
Console.WriteLine("Event sent from " + sender);
}
...
textArea.KeyPress += LogEvent;
This works even though Control.KeyPress is an event of type KeyPressEventHandler. C# and .NET don't mind that the signature of LogEvent doesn't exactly match the signature of KeyPressEventHandler - it's compatible enough.
Admittedly this would still be feasible if we didn't have EventArgs at all (you could just use object) but given the EventArgs class and the pattern, it makes sense to derive your own event arguments from EventArgs.
What is really important here is that you can easily UPGRADE your event later to have MORE details and don't break existing decoupled listeners.
Here is a example of how you might use your code:
public class MyClass () {
public event EventHandler<ClickedEventArgs> ClickedEvent = delegate {}; //Register the event
protected void SomethingWasClicked(int x, int y) {
ClickedEvent(this, new ClickedEventArgs(x,y)); //Invoke the event that is subscribed to
}
}
public class AnotherClass () {
public AnotherClass () {
MyClass mClass = new MyClass();
mClass.ClickedEvent += new EventHandler(mClass_clickedEvent);
}
protected void mClass_clickedEvent(object sender, ClickedEventArgs e) {
//Retrieve the X parameter that was passed from the MyClass instance
int x = e.X;
}
}