Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error "Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal"

Tags:

c#

.net

I tried to make a class as private and got this Error "Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal"

I got its meaning but I want to ask why this is not allowed? Are all access modifires not applicable on Class? Why I can't make a class private, protected or protected internal?

like image 225
user576510 Avatar asked Sep 11 '11 16:09

user576510


People also ask

Can we have protected element as a namespace member?

Elements defined in a namespace cannot be explicitly declared as private, protected, protected internal or private protected.

Can a class be private in C#?

Class members, including nested classes and structs, can be public , protected internal , protected , internal , private protected , or private . Class and struct members, including nested classes and structs, have private access by default. Private nested types aren't accessible from outside the containing type.


3 Answers

Because private means that the member is only visible in the containing class. Since a top-level class has no class containing it it cannot be private (or protected). (Internal or public are valid modifiers though).

What would you want private to mean on a top-level class?

Of course all modifiers apply to nested classes, i.e. a class defined within another class.

like image 127
DeCaf Avatar answered Oct 19 '22 21:10

DeCaf


You can use only public or internal in the Namespace level

like image 14
John Avatar answered Oct 19 '22 19:10

John


As Abatonime said, you can only use public or internal in the Namespace level.
private, protected, or protected internal can only be used in the Class level.

This works

namespace X
{
    class A
    {
        // class code here

        private class B // this class is an inner class
        {
            // class code here
        }
    }
}

This won't

namespace X
{
    class A
    {
        // class code here
    }

    private class B // this is a class inside a namespace
    {
        // class code here
    }
}
like image 5
SNag Avatar answered Oct 19 '22 21:10

SNag