In this article we are going to discuss Modifiers and Access Specifiers in C#. There are many blogs, articles are available on the internet regarding Modifiers and Access Specifiers but in this particular article I will try to explain to you with as much as simplest and realistic examples so you can get a clear idea of the Modifiers and Access Specifiers use in C#.
In C#, modifiers and access specifiers are often used interchangeably, but they refer to different concepts. Here’s a breakdown of the differences:
Access Specifiers (Access Modifiers)
Access specifiers (also known as access modifiers) define the visibility and accessibility of classes, methods, and other members. They control which parts of your code can see and use certain components. The main access specifiers in C# are:
Example
public class MyClass
{
private int privateField; // Accessible only within MyClass
protected int protectedField; // Accessible within MyClass and derived classes
internal int internalField; // Accessible within the same assembly
protected internal int protectedInternalField; // Accessible within the same assembly or derived classes
public int publicField; // Accessible from any code
}
Modifiers
Modifiers are keywords that provide additional information about the behavior and characteristics of classes, methods, properties, and other members. They do not necessarily relate to accessibility but to the behavior and usage of the members. Some common modifiers in C# include:
Example
public class MyClass
{
public static int staticField; // Static field
public readonly int readonlyField; // Readonly field
public const int constantField = 42; // Constant field
public virtual void VirtualMethod() { } // Virtual method
public abstract void AbstractMethod(); // Abstract method (only in abstract classes)
public sealed void SealedMethod() { } // Sealed method (prevents further overriding)
}
public partial class PartialClass // Partial class definition (could be in another file too)
{
// Partial implementation
}
Difference