Lyrk
Lyrk

Reputation: 2000

Declaring private variable inside Main

class Program
{
    static void Main(string[] args)
    {
        private int panda=3;            
    }
}

Compiler spits 4 errors when I do this. Declaring private variable in main is forbidden? Why?

Upvotes: 0

Views: 4539

Answers (4)

Vahid Farahmandian
Vahid Farahmandian

Reputation: 6568

Based on the MSDN that says:

The private keyword is a member access modifier. Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared

you can not define a variable as Private inside a method. Logically, declaring a variable as Private inside method does not make a sense.

Referense: https://msdn.microsoft.com/en-us/library/st6sy9xe.aspx

Upvotes: 1

Rahul
Rahul

Reputation: 77866

Yes that's cause it's a local variable (local to the function Main and not accessible by any other method/procedure unless passed explicitley) and not a class member. It just should be

int panda=3; 

Or if you meant to be class member then declare it in class scope.

class Program
{
    private int panda=3; 

Upvotes: 0

Vicky
Vicky

Reputation: 2097

Variables declared inside a block (i.e. code between two curly braces) are only visible inside this block, so there is no sense in declaring them private, public or protected.

Class A
{
private static int x=0;//make sense

 static void Main(string[] args)
    {
       private static int x=0; //does not make sense
    }
}

Upvotes: 2

Sinnich
Sinnich

Reputation: 342

Your private is inside a method not a class.

class Program
{
    private static int panda=3;            
    static void Main(string[] args)
    {

    }
}

Upvotes: 1

Related Questions