The name does not exist in the current context? - c#

I'm a total noob in c#, since today. I couldn't find a good tutorial or anything, that could solve this obviously dumb problem. Basically, I try to translate a program from Python to C#. Normally in Python I define constants in the constructor. Where the hell should I put them in c#? I tried to put them in the constructor then I put them in Main(), because there was this error. But the error persists.
static void Main(string[] args)
{
var _top = 0
...
}
public string[] topToken()
{
if (_top < _tokens.Count())
{ return _tokens[_top];}

_top is declared inside Main, so it's not going to have visibility inside the topToken method. It's a local variable, scoped only to Main.
To give your variables visibility for the entire class, you need to declare them outside of any method.
Ex:
public class SomeClass
{
public int someVariable; // all methods in SomeClass can see this
public void DoIt() {
// we can use someVariable here
}
}
Note, by makeing someVariable public, it also means other we can access it directly. For example:
SomeClass x = new SomeClass();
x.someVariable = 42;
If you want to prevent this and only allow the methods/properties/etc. of the class to be able to see the someVariable variable, you can declare it as private.
In cases where you need a public variable, it's usually best to declare it like this (this is an example of an auto-implemented property):
public class SomeClass
{
public int SomeVariable { get; set; }
public void DoIt() {
// we can use SomeVariable here
}
}
This uses

if you want _top to be available outside of the Main method, place it here:
int _top = 0; //here instead
static void Main(string[] args)
{
...
}
public string[] topToken()
{
if (_top < _tokens.Count())
{ return _tokens[_top];}
}

Change your code to this:
const int _top = 0;
static void Main(string[] args)
{
...
}
public string[] topToken()
{
if (_top < _tokens.Count())
{ return _tokens[_top];}
To make _top accessible throughout your class you have to declare it as a field or a constant. A field requires actual storage while a constant is simply replaced by the actual value by the compiler. As you described _top as a constant I decided to declare it as such.
If you need a field and not a constant you have to declare it static because it is accessed in a static method:
static int _top = 0;
Because there is no public or protected in the declaration of _top it is private to the class. If you prefer you can add private in front of the declaration but that will be the default if the visibility is missing.

Related

can't use public access modifier

Sorry if this is a really stupid question, but I am messing around and fiddling with what I am learning from YouTube beginner tutorials and I'm kind of lost here. can anyone let me know why using the public access specifier before the fields break everything?
namespace ConsoleApp1
{
class Methods
{
static void Main(string[] args)
{
public int _first, _second, _third, _fourth, _fifth;
for (int i=1;i<=5;i++)
{
Console.WriteLine("Enter {0}st number:", i);
Console.ReadLine();
switch (i)
{
case 1:
_first = i;
break;
}
}
}
The problem is the scope.
The fields (inside functions or methods it's better use variable) in the scope of a function cannot be "public" or "protected" or... No, are private to the container scope, and, of course, doesn't need access word.
If you make a field outside the function you can make it public, private, internal... etc...
You cannot make fields out of object or structs.
namespace ConsoleApp1
{
public int _secondThing // baaaad
class Methods
{
public static int _thing; //good
int _thing; //good, it's private;
private int _thing; //good, it's the same
public int _firstThing; //good
static void Main(string[] args)
{
public int _first, _second, _third, _fourth, _fifth; //baaad
int _first, _second; //good
}
}
}
As DrkDeveloper mentioned it´s a question of the scope of your variables. Depending on where you define a variable it only exists within that specific scope and all of its child-scopes, but not in parent-scopes. So defining somethin at class-level makes it accessable in the entire class, this is in all of its members. Defining a variable within a member such as a method on the other hand makes that variable existing only in that specific scope - in that method. You can´t access it from anywhere outside its scope.
Your first code without the access-modifier works, because the variables are defined within that method - we call them local variables. The second code with the access-modifiers would turn those variables into members (fields in this case) of the class. So you´d define a member in a method that should have a class-scope. This of course does not work.
So you either leave your variables local, or make them public static within your class.
namespace ConsoleApp1
{
class Methods
{
public int _first, _second, _third, _fourth, _fifth;
static void Main(string[] args)
{
for (int i=1;i<=5;i++)
{
Console.WriteLine("Enter {0}st number:", i);
Console.ReadLine();
switch (i)
{
case 1:
_first = i;
break;
}
}
}
}
}

C# class variable initialization

I want to declare and initialize a string variable that is local to a class but can be accessed by all functions of the class. Fyi, this is an app for a gui which will be making use of several text files in folders. I am trying to set a string variable containing the project directory path so it can be accessed by all the functions within this class.
I have provided an portion of my code including the function that sets the path along with a function that uses the string variable when set.
public class Program
{
private string DirectoryPath;
public static void Main()
{
setPaths();
SetGroundTempArray();
}
public static void setPaths()
{
DirectoryPath = Directory.GetCurrentDirectory();
}
public static void SetGroundTempArray()
{
string groundtempfile = "\\groundtemp.txt";
string groundtempdir = "\\Text Files";
string groundtempFP = DirectoryPath + groundtempdir + groundtempfile;
}
}
Your code won't compile.
You should declare the DirectoryPath class field as static:
private static string DirectoryPath;
So you are currently on the right track. In C# we call them Fields
Fields typically store the data that must be accessible to more than
one class method and must be stored for longer than the lifetime of
any single method
In your case private string DirectoryPath; is a field. And you are following the good practice of making it private.
Also as noted you have all methods as static so you need to make the Field variable static as well to access it
private static string DirectoryPath;
A field can optionally be declared static. This makes the field
available to callers at any time, even if no instance of the class
exists.
As given in your example, you have done it right as the functionality you want. But you may need to learn more about the usage of static keywords in C#. You can learn more about it at MSDN
Here's a intercept about your code, that might clear your concept.
As DirectoryPath is used by a static method in your progream, you must need to declare this variable as static also because of, setPaths method is used in static Main, and Main is the topmost level static class that don't requires the instance to be created of the Program Class. and that is why, Main method would require all the methods or variable or fields is being used inside the method must be declared as static.
public class Program
{
private static string DirectoryPath;
public static void Main()
{
setPaths();
SetGroundTempArray();
}
public static void setPaths()
{
DirectoryPath = Directory.GetCurrentDirectory();
}
public static void SetGroundTempArray()
{
string groundtempfile = "\\groundtemp.txt";
string groundtempdir = "\\Text Files";
string groundtempFP = DirectoryPath + groundtempdir + groundtempfile;
}
}
Add static in front of string.
class Program
{
//add static in front of string
static String a = "Hello";
static void Main(string[] args)
{
h();
Console.ReadKey();
}
public static void h()
{
Console.WriteLine(a);
}
}

declaring a variable global in c#

I am developing a windows phone 7 app and need to declare variables as global so that the information they carry can be used anywhere in the application.
I tried this by declaring variables as public static. I tried almost all the possibilities i could think of but none worked. can we make variables global? If yes, how?
If you want a global variable, public static is what you need. However, you should prefer using properties rather than public variables:
public class GlobalData {
private static string someString = "Hello, world!";
public static string SomeString {
get {return someString;}
set {someString = value;}
}
}
You refer to this global variable using a fully qualified name, like this:
GlobalData.SomeString = "Quick brown fox";
Console.WriteLine("Global variable value is '{0}'", GlobalData.SomeString);
Did you try putting your global variables inside of a public class and referencing them by the class name and than the variable name?
public static class GlobalVariables {
public static int MrGlobalInt = 5;
}
...
GlobalVariables.MrGlobalInt = 10;

Static code blocks

Going from Java to C# I have the following question:
In java I could do the following:
public class Application {
static int attribute;
static {
attribute = 5;
}
// ... rest of code
}
I know I can initialize this from the constructor but this does not fit my needs (I want to initialize and call some utility functions without create the object).
Does C# support this? If yes, how can I get this done?
Thanks in advance,
public class Application
{
static int attribute;
static Application()
{
attribute = 5;
} // removed
}
You can use the C# equivalent static constructors. Please don't confuse it with a regular constructor. A regular constructor doesn't have a static modifier in front of it.
I am assuming your //... rest of the code need to be also run once. If you don't have such code you can just simply do this.
public class Application
{
static int attribute = 5;
}
You just can write a static constructor block like this,
static Application(){
attribute=5;
}
This is what I could think of.
In your particular scenario, you could do the following:
public class Application {
static int attribute = 5;
// ... rest of code
}
UPDATE:
It sounds like you want to call a static method. You can do that as follows:
public static class Application {
static int attribute = 5;
public static int UtilityMethod(int x) {
return x + attribute;
}
}
I find something else useful. If your variable needs more than one expressions/statements to initialize, use this!
static A a = new Func<A>(() => {
// do it here
return new A();
})();
This approach is not limited on classes.
-A static constructor doesn't have any parameter.
-A static class can contain only one static constructor.
-A static constructor executes first when we run the program.
Example:
namespace InterviewPreparation
{
public static class Program
{ //static Class
static Program()
{ //Static constructor
Console.WriteLine("This is static consturctor.");
}
public static void Main()
{ //static main method
Console.WriteLine("This is main function.");
Console.ReadKey();
}
}
}
Output:
This is static constructor.
This is main function.

How I will use the following static variable from other class?

I have a class like following:
public class Trainee
{
private static int numberOfTrainee = 30;
private string traineeName;
private string tarineeId;
}
Now I want to access the static data "numberOfTrainee" in the following class without creating a object of "Trainee" class and I don't want to write getter for "numberOfTrainee". Because, static member can be used only using "." operator.
public class TraineeUI : Form
{
private void showButton_Click(object sender, EventArgs e)
{
// I want to access "numberOfTrainee" here. Something like following:
// MessageBox.Show("Total number of trainee is: " );
}
}
If you don't want a getter for it, the only way to use it from elsewhere will be to increase the visibility, like so:
public class Trainee
{
public static int NumberOfTrainee = 30;
private string traineeName;
private string tarineeId;
}
// Other code.
MessageBox.Show("Total number of trainee is: " + Trainee.NumberOfTrainee);
However, I would recommend against doing this with a field that can change. Unless it's a constant, you should define a property to control access to this field, static or not.
You should make a property, like this:
public class Trainee
{
private static int numberOfTrainee = 30;
public int TraineeCount { get { return numberOfTrainee; } }
private string traineeName;
private string tarineeId;
}
Note that you may want to consider thread safety... it's possible that this simple implementation will give stale results in a multi-threaded environment. Making numberOfTrainee volatile would solve this.
Further, note that by making this a property rather than giving direct access to the field, you:
Can add extra logic should you ever wish to
Can make the property readonly, but modify the field from within the class
Keep encapsulation intact: a property is part of the API of a class, whereas a field is an implementation detail
I don't want to recycle what others have said, but....
You need to look at access modifiers. You say you don't want to make numberOfTrainee public, but you can make it internal. That way, if Trainee and TraineeUI are in the same assembly, than TraineeUI can access the field of Trainee without the field being exposed to types outside the assembly.
I would make it a property instead of a field though.
Well, either you could make it public and then just calll it with:
Trainee.numberOfTrainee
Or you could create a static readonly property.
public static int NumberOfTrainee
{
get
{
return numberOfTrainee;
}
}

Categories