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"];
Related
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.
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.
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'm new to C# - this is nearly my first program. I'm trying to create some public static variables and constants to use anywhere in the program. The - wrong - way I have tried is to declare them in a separate class in the same namespace but they are out of context for the main program. It's a WPF application. The code looks like this:
namespace testXyz
{
class PublicVars
{
public const int BuffOneLength = 10000;
public static int[] Buff1 = new int[BuffOneLength];
public const int BuffTwoLength = 2500;
public static int[] Buff2 = new int[BuffTwoLength];
private void fillBuff1()
{
Buff1[0] = 8;
Buff1[1] = 3;
//etc
}
private void fillBuff2()
{
Buff2[0] = 5;
Buff2[1] = 7;
//etc
}
}
}
Second file:
namespace testXyz
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public static int isInContext = 0;
int jjj = 0, mmm = 0;
private void doSomething()
{
isInContext = 5; // this compiles
if (jjj < BuffOneLength) // "the name 'BuffOneLength' does not exist in the current context"
{
mmm = Buff2[0]; // "the name 'Buff2' does not exist in the current context"
}
}
}
}
My actual program is much longer of course. I created the above WPF application exactly as shown to test this problem and I got these errors, also occurring in the real program. I really don't want to fill the arrays in the main program as they are very long and it would mean much scrolling. I also want to have one place where I can declare certain public static variables. What is the right way to do this?
You have to either specify class:
// BuffOneLength from PublicVars class
if (jjj < PublicVars.BuffOneLength) {
...
// Buff2 from PublicVars class
mmm = PublicVars.Buff2[0];
or put using static:
// When class is not specified, try PublicVars class
using static testXyz.PublicVars;
namespace testXyz {
public partial class MainWindow : Window {
...
// BuffOneLength - class is not specified, PublicVars will be tried
if (jjj < BuffOneLength) {
mmm = Buff2[0];
You can't access a static variable that is in another class by just calling the variable. You need to first go thru the class that contains it in your case it would be
PublicVars.BuffOneLength
and
PublicVars.Buff2[0]
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());
}