#790 – Property get and set Accessors Can Have Different Access Modifiers

When you implement a property in a class, you can specify different access modifiers for the get vs. set accessors.  This is true whether you are implementing the property yourself, or using an automatic property.

Different combinations of access modifiers include:

  • get/set both public – client can read/write property value
  • get/set both private – client has no access to the property
  • get public, set private – property is read-only
  • get private, set public – property is write-only
        // get/set both public
        public string Name { get; set; }

        // get/set both private
        private string SecretName { get; set; }

        // public get => read-only
        public string CalcName { get; private set; }

        // public set => write-only
        public string WriteOnlyName { private get; set; }

#699 – Types Are Implicitly Internal

When you define a type in C#, you can define its accessibility as either public or internal.  Public types are visible to all code.  Internal types are visible only to code within the same assembly.

By default, if you don’t include an access modifier when defining a type, the type’s accessibility will be internal.

In the example below, the Dog class will be visible only to code within the same assembly.

    // No access modifier => type is internal, visible
    //   only to code within the same assembly.
    class Dog
        // Public properties
        public string Name { get; set; }
        public int Age { get; set; }

        // Instance constructor
        public Dog(string name, int age)
            Name = name;
            Age = age;

        public void Bark()

#697 – Encapsulation is Managed through the Use of Access Modifiers

Encapsulation is one of the core principles of object-oriented programming.  Encapsulation is the idea of hiding implementation details of a class from the users of that class and only exposing a public interface.

When you author a class in C#, you can decide which class members (e.g. properties, fields, methods, events, etc) are visible to users of the class.  You do this by using access modifiers to indicate the accessibility of each class member.

Making some class members private allows hiding data from the users of the class, which supports the principle of encapsulation.  Encapsulation is also achieved by preventing access to methods whose use are internal to the code in the class.

#314 – Access Modifiers Are Not Allowed on Static Constructors

Because you can’t call a static constructor directly, you can’t include an access modifier (e.g. public, private) when defining a static constructor.  Static constructors are defined without access modifiers.

        static Dog()
            Motto = "We serve humans.  And lick ourselves.";

The compiler will generate an error if you try to include an access modifier.