Home » c# » Why is ;; allowed after a local variable declaration, but not after a field declaration?

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

Posted by: admin November 29, 2017 Leave a comment

Questions:

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.

enter image description here

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

enter image description here

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.

Answers:

; 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.

Questions:
Answers:

; 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.

Questions:
Answers:

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: When do you use scope without a statement in C#?

It is kind of similiar, but not completely, it will help you to understand why

int a = 1;;;

is valid.

Questions:
Answers:

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.

Questions:
Answers:

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.