C# – Default access modifiers

Classes (and other types) are internal by default. Class members (methods/properties/fields) are private by default.

These defaults are applied when you don’t explicitly declare an access modifier. Here’s an example:

class Coder
{
    int workDone;
    string Language { get; set; }
    void DoWork()
    {
        //do stuff
    }
}
Code language: C# (cs)

Since the access modifiers aren’t declared, it uses the defaults. The class is internal while all of the members are private. This is almost never what you really want. It’s better to explicitly declare the access modifiers you want to use (even if they are the same as the defaults). Here’s an example:

internal class Coder
{
    private int workDone;
    internal string Language { get; set; }
    internal void DoWork()
    {
        //do stuff
    }
}
Code language: C# (cs)

Default access modifiers for property getters/setters

By default, property getters/setters have the same access modifier as the property. Here’s an example:

public class Coder
{
    public string Language { get; set; }
}
Code language: C# (cs)

The property is public, so the getter/setter are public by default. This behavior is nice and convenient.

You can explicitly declare the access modifier for a getter/setter when you want it to be more restrictive than the property. The most common reason to do this is to make a public property have a private setter. Here’s an example:

public class Coder
{
    public string Language { get; private set; }

    //rest of class
}
Code language: C# (cs)

Note that you can’t make the getter/setter less restrictive than the property. For example, an internal property can’t have a public getter/setter, because public is less restrictive than internal.