C# - Access modifiers and property accessors

I recently wrote about the init property accessor and property accessors in general. I was wondering for a second how access modifiers and accessors were different, they have very similar names. They seem similar but differ in what they do and when they were introduced, let us start by defining both.

Access Modifiers

Access Modifiers are common in most programming languages. They define when a member, method, property, class etc. can be accessed from another part of your code base. The most common are:

Public: The member is accessible from any other part of the code base.
Private: The member is only accessible within its declaring class or struct.
Protected: Same as private but can be accessed within a derived class
Internal: The member is only accessible within the same assembly.

You can for example set this access level on a class:

<public, private, protected or internal> class MyClass
{

}

Access Modifiers have always been around in C#.

Property accessors

Property accessors or just "accessors" are used to get or set values of properties. for example:

public string SomeProperty { get; set; }

In the above get and set are property accessors. get defines that you can retrieve the value of SomeProperty and set defines that you can assign a value to it. You can mix access modifiers and accessors by for example having a private set and a public get:

public string SomeProperty { get; private set; }

In the above you can only set the property within the class as the set has a private access level. There are three property accessors:

  • get: Defines an accessor that returns the properties value
  • set: Defines an accessor that sets the properties value
  • init: Defines an accessor that sets the properties value, but only at initilisation time.

Conclusion

In short, access modifiers define the visibility of classes and members, while property accessor dictates the access and manipulation of property values. They are not the same and they are not exclusive to one another.