Tushar Kukreti Tushar Kukreti - 8 months ago 67
C# Question

Why public variables are not allowed inside a method or any block except class in c#?

A very strange issue I faced that when I try to declare a variable say of type

with public keyword inside a method of a class then a compile-time error is being thrown by the compiler with no proper explanation.

Consider below piece of code:

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

According to my consideration when we decalre a variable as public inside a method, it excepts that method to be a class, struct or interface.

And that's what my question is that why C# is restricting us to to declare a variable as public inside method. What's the problem with it?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download