Why;; allowed after declaring a local variable, but not after declaring a field?

I saw this strange behavior, and I wonder if there is a reasonable explanation for this:

When I (accidentally) added an extra / additional semicolon to a local variable of a function, for example:

public void MyMethod () { int a = 1;; Console.WriteLine(a); //dummy } 

It compiles, but shows that it is superfluous.

enter image description here

But when I did this with fields (also by accident), I got an error (compilation):

enter image description here

Question

Is there a reason for this limitation in the fields?

Nb I already know another limitation thing, not to allow var with fields. But here it is something else.

+59
c # compiler-errors
Dec 22 '14 at 11:28
source share
5 answers

; alone is an operator (empty operator), but only declarative statements are allowed in the class body; other types of operators can appear only in the body of the method.

+82
Dec 22 '14 at 11:32
source share

; is an empty statement. And in the class domain, only statement declarations are allowed. The class body is defined in C# Specification 5.0, Β§10.1.6 Class Body

 class-body: { class-member-declarations } 

For example, you cannot initialize a field in a separate statement:

 class Foo { int x = 2; // this is allowed x = 5; // this is not } 

This way you can only declare fields and other members, but you cannot use other instructions in the body of the class.

+26
Dec 22 '14 at 11:52
source share

This is not part of the declaration of a local variable, it is an application in itself, as pointed out by Thomas.

It's really:

 public void MyMethod () { ;;; int a = 1; ; Console.WriteLine(a); //dummy ;; } 

The idea of ​​a half-dozen expression is to allow such constructs:

 while(mycondition) ; 

It makes no sense to allow it into the body of the class; this does not bring any additional value.

TL; DR; it has nothing to do with variable / field declaration

You might also want to take a look at this thread: When do you use a scope without instructions in C #?

It looks like similarity, but not completely, it will help you understand why

int a = 1;;;

.

+6
Dec 22 '14 at 11:39
source share

In the first case, the compiler sees the no-op operator. It doesn't matter what the second ; appears after variable declaration.

In the second case, the compiler sees an attempt to create an empty declaration that is not allowed.

+3
Dec 22 '14 at 11:33
source share

Inside the body, redundancy functions; this is an empty statement, but there is an undeclared field in the class declaration and it is not allowed.

-four
Dec 25 '14 at 21:47
source share



All Articles