Introduction
Access modifiers are keywords used to specify the declared accessibility of a member or a type. These define the permission level to type members ( Methods, Properties, Events, Variables).
Background
All type and type members have an accessibility level which controls whether they can be used by the code in the same assembly in which the type declared or the code in the other assembly.
Points of Interest
- Access modifiers are not allowed on namespaces. Namespaces have no access restrictions.
- Top-Level types, which are not nested into other types, can only have internal or public accessibility. The default accessibility for these types is internal.
- The accessibility of a nested type depends on its accessibility domain, which is determined by both the declared accessibility of the member and the accessibility domain of the immediately containing type.
- Private,Protected and Protected Internal class we can't declare explicityly within namespace.
- Struct members cannot be protected because the struct cannot be inherited.
- The drived class can't have higher accessibility than its base class, i.e. you can't have a public class that drived from a internal class.
- The accessibility of a member can never be higher than the accessibility of its containing type.
- Interface can only be public or internal. And default to internal.
- Enum are default to public so not accept any modifer.
- Delegates are default to internal.
Description
Given below are the major access modifiers used with type or type members.
- Public
- Protected
- Internal
- Protected Internal
- Private
Public
Using Public, access is not restricted; it means type or type members are accessible by the code in the same or other assembly that referenced it.
public class SampleClass1
{
// Public variable
public static int myPublicInt;
}
class Program
{
static void Main(string[] args)
{
// Access to SampleClass1 fields
SampleClass1.myPublicInt = 1; // Access is unlimited
Console.WriteLine("Press any key to exit!");
Console.ReadLine();
}
}
Protected
Using Protected, access is limited to the class which declares that member and the immediate class which inherits that class. A protected member of a base class is accessible in a drived classs only if the access takes place through the derived class type.
Example
class ProtectedSample
{
protected string Name = string.Empty;
protected void Display()
{
Console.WriteLine("Name: " + Name);
}
}
class Drived : ProtectedSample
{
Drived()
{
this.Name = "John"; // Accessible
}
// Method will call ProtectedSample class Display method
public void DisplayName()
{
this.Display();
}
}
class Other
{
Other()
{
(new ProtectedSample()).Name = "Mike"; // Error: Inaccessible due to its protection level
}
}
vineeta suryanPosted Jul 18, 2017, 2:28 PM
Struct can be protected internal?
vineeta suryanPosted Jul 12, 2017, 9:00 AM
Good and understandable explaination...thx