A very strange issue I faced that when I try to declare a variable say of type
string
public class MyClass
{
public string publicVarInClass= null; // No error here. Works fine
public void MyMethod()
{ // Error shown here is "Expected } "
public string publicVarInMethod = null; // not allowed, but no error is shown in this line. WHY?
try // Error shown here is Invalid token 'try' in class, struct or interface declaration
{
//some code here
}
}
}
There is a difference between variables and fields. Only fields have access protection, while variables cannot be accessed at all outside method's body.
"Public variables" in C# are called fields. C# allows field declarations to appear only in the body of a class or a struct. Fields are parts of an object definition, which are either attached to an instance, or shared among all instances.
Variables inside methods, on the other hand, are not fields. Being local to a method body, they do not need access protection. Their lifetime and scope are limited inside the method, so there is no way for any code outside of that method to access local variables.