Default access modifiers in C#
By Tan Lee Published on Mar 05, 2025 107
These default access modifiers apply when you don’t specify one explicitly.
class Programmer { int hoursWorked; string ProgrammingLanguage { get; set; } void Code() { // do work } }
In this example, because access modifiers are not declared, the class has an internal
access modifier, and all the members (like hoursWorked
, ProgrammingLanguage
, and Code
) are private by default.
internal class Programmer { private int hoursWorked; internal string ProgrammingLanguage { get; set; } internal void Code() { // do work } }
Default Access Modifiers for Property Getters/Setters
By default, the access modifiers for property getters and setters match that of the property itself.
public class Programmer { public string ProgrammingLanguage { get; set; } }
Here, the ProgrammingLanguage
property is public, so both the getter and setter are also public by default.
However, if you want to control access more tightly, you can explicitly specify different access modifiers for the getter and setter. A common use case is having a public property with a private setter.
public class Programmer { public string ProgrammingLanguage { get; private set; } // other class members }
In this case, the ProgrammingLanguage
property is publicly readable, but its setter is private, meaning it can only be modified within the class.
Important Note: You cannot make the getter/setter less restrictive than the property itself. For instance, if the property is internal
, you can’t make the getter or setter public
, as public access would be less restrictive than internal access.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization