Reputation: 1817
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];}
Upvotes: 0
Views: 3283
Reputation: 106796
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.
Upvotes: 0
Reputation: 55424
_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
Upvotes: 2
Reputation: 24385
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];}
}
Upvotes: 0