Array declaration

mp3909

Well-known member
Joined
Apr 22, 2018
Messages
61
Location
UK
Programming Experience
3-5
I am wondering why the following gives an error:


C#:
public class Program
{
    public static void Main(string[] args)
    {
       public int[] numbers = new int[5];

    }
}
 
Ok, so I gathered that if I remove the "public" keyword from the array declaration, then the error goes away.

C#:
public class Program
{
    public static void Main(string[] args)
    {
        int[] numbers = new int[5];
    }
}

but I don't understand the reasoning behind this?
 
public is an access modifier. Access modifiers specify from where you can access something and so are only valid on types or members. Your variable is a local, i.e. declared inside a method. Anything declared inside a method is only accessible to code inside that method so access modifiers would be meaningless.

In the case of types, e.g. classes and structures, the public access modifier means that the type is accessible to code outside the assembly it is declared in. In the case of members, e.g. methods and properties, public means that the member is accessible outside the type it is declared in. By that logic, public on a local variable would mean accessible outside the method it's declared in, which is not possible and thus nonsensical and thus not allowed. Local variables are always effectively private, i.e. accessible to code only at the same scope, and so no access modifier is required or allowed.
 

Latest posts

Back
Top Bottom