Coder Perfect

What are the access modifiers in C# by default?


For classes, methods, members, constructors, delegates, and interfaces, what is the default access modifier?

Asked by Surya sasidhar

Solution #1

In C#, everything’s default access is “the most restricted access you might designate for that member.”

So for example:

namespace MyCompany
    class Outer
        void Foo() {}
        class Inner {}

is equivalent to

namespace MyCompany
    internal class Outer
        private void Foo() {}
        private class Inner {}

Making one part of a property (typically the setter) more restricted than the declared accessibility of the property itself is an exception to this rule:

public string Name
    get { ... }
    private set { ... } // This isn't the default, have to do it explicitly

This is what section 3.5.1 of the C# 3.0 specification says:

(Note that nested types go under the “class members” or “struct members” sections, and hence have private visibility by default.)

Answered by Jon Skeet

Solution #2

top level class: internal
method: private
members (unless an interface or enum): private (including nested classes)
members (of interface or enum): public
constructor: private (note that if no constructor is explicitly defined, a public default constructor will be automatically defined)
delegate: internal
interface: internal
explicitly implemented interface member: public!

Answered by John Buchanan

Solution #3

Short answer: as little access as possible (see Jon Skeet’s response).

Long answer:

Enumeration, delegate accessibilities, and non-nested types (may only have internal or public accessibility)

Accessibilities of nested types and members

The accessibility domain of a nested type is determined by both the declared accessibility of the member as well as the accessibility domain of the immediately containing type. The accessibility domain of a nested type, on the other hand, cannot be larger than that of the contained type.

Note that CIL also offers a protected and internal option (rather than the present protected “or” internal), although I’m not aware of it being implemented in C#.

See: (Man I love Microsoft URLs…)

Answered by Ben Aston

Solution #4

Access Modifiers (C# Programming Guide) is a good place to start.

Answered by Adriaan Stander

Solution #5

Internal is the default class.

By default, the interface is set to Internal.

By default, Struct is set to Internal.

Answered by xoxo

Post is based on