Hsen Shamseddine
Hsen Shamseddine

Reputation: 33

Visual Studio issue with recognising variables

Okay so in short:

I declare a variable, say

string str = "Random";

then I try to perform any sort of operation whatsoever, say

str.ToLower();

And neither visual studio, nor intellisense recognise it at all. VS gives me the name "str" does not exist in the current context. This happened right after I installed xamarin but I'm not sure if it's related.

Also this issue would not occur if I was inside a method, just when I'm directly inside a class.

This is my code:

public class Program {
   public void randomMethod() {
      string str2 = "Random";
      str.ToUpper(); //this line shows no errors
   }

   string str = "Random";
   str.ToLower(); //this line does show the error
}

str would be underlined red and the warning mentioned above would appear.

Does anybody know what's going on?

Upvotes: 0

Views: 71

Answers (2)

Austin T French
Austin T French

Reputation: 5131

It is a scope issue:

public class Program {
   public void randomMethod() { //method scope starts
      string str2 = "Random";
      str.ToUpper(); //this line shows no errors
   } //method scope ends

   string str = "Random";  //this is a class field, but is missing an accessibility level
   str.ToLower(); //this line SHOULD show an error, because you can't do this in a class
}

Upvotes: 1

pm100
pm100

Reputation: 50190

you even point the issue out yourself

you cannot do this

public class Program {
   string str = "Random";
   str.ToLower(); //this line does show the error
}

when would you expect that code to run?

You must put executable code inside a function. You point out that this works.

I cannot propose a fix since I do not know what you are trying to do.

Upvotes: 2

Related Questions