Why is ;; allowed after a local variable declaration, but not after a field declaration?
C#Compiler ErrorsC# Problem Overview
I saw this weird behaviour and I wonder if there's a reasonable explanation for this:
When I put by ( by accident) an additional/extra semicolon in a function's local variable like:
public void MyMethod ()
{
int a = 1;;
Console.WriteLine(a); //dummy
}
It does compile but it shows that it's redundant.
But when I did that with fields (also by accident) , I got an error (compilation) :
Question
Is there any reason for this restrictiveness in fields ?
Nb I already know the other restrictiveness thing for not allowing var
with fields. But here it's something different.
C# Solutions
Solution 1 - C#
;
alone is a statement (empty statement), but only declaration statements are allowed in the body of a class; other kinds of statement can only appear in the body of a method.
Solution 2 - C#
;
itself is an empty statement. And in class scope only the declaration statements 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 can't initialize a field in a separate statement:
class Foo
{
int x = 2; // this is allowed
x = 5; // this is not
}
So you can only declare fields and other members but you can't use other statements in a class body.
Solution 3 - C#
It is not part of local variable declaration, it's a statement by itself, as indicated by Thomas.
This is valid:
public void MyMethod ()
{
;;;
int a = 1;
;
Console.WriteLine(a); //dummy
;;
}
The idea of semi-colon statement is to allow such constructs:
while(mycondition) ;
It does not make sense to allow it in in the body of class, it brings no extra value.
TLDR; this has nothing to do with variable/field declaration
You might want to take a look at this thread too: https://stackoverflow.com/questions/27458124/when-do-you-use-scope-without-a-statement-in-c/27458354#27458354
It is kind of similiar, but not completely, it will help you to understand why
int a = 1;;;
is valid.
Solution 4 - C#
In the first case the compiler sees a no-op statement. It doesn't matter that the second ;
comes after a variable declaration.
In the second case the compiler sees an attempt to create an empty declaration which isn't allowed.
Solution 5 - C#
Inside the body of a function the redundant ; is an empty statement but in the class declaration is an undeclared field and it not allowed.