Access Modifiers in C#

Access modifiers play an important rule in forcing programmers to apply to a given object-oriented design. They hide members to prevent undefined access, define which members take part in the inheritance process and what objects are visible outside of a library.

Right here we already have to note that all restrictions placed by modifiers are only artificial. The compiler is the only protector of those rules. This means that those rules will not prevent unauthorized access to, e.g., a variable during runtime. Therefore setting access modifiers to spawn some kind of security system is certainly a really bad idea. The main idea behind those modifiers is the same as with object-oriented programming: Creating classes that encapsulate data and force other programmers in a certain pattern of access. This way, finding the right way of using certain objects should be simpler and more straight forward.

C# knows a whole bunch of such modifier keywords. Let’s have a look at them with a short description:

  • private, declares that a member is neither visible from outside the object, nor does it take part in the inheritance process.
  • protected, declares that a member is not visible from outside the object, however, the member takes part in the inheritance process.
  • internal, declares that a member or type is visible outside the object, but not outside the current library.
  • internal protected, has the meaning of internal OR protected.
  • ublicp, declares that a member or type is visible everywhere.

Below is a program for your reference:

using System;

//No modifier, i.e., the class Program is internal
class Program
{
//No modifier, i.e., the method Main() is private
static void Main()
{
MyClass c = new MyClass();
//Works
int num = c.WhatNumber();
//Does not work
//int num = c.RightNumber();
}
}

//MyClass is visible from this library and other libraries
public class MyClass
{
//This one can only be accessed from MyClass
private int a;

//Classes inheriting from MyClass can access b like MyClass can
protected int b;

//No modifier, i.e., the method RightNumber() is private
int RightNumber()
{
return a;
}

//This will be seen from the outside
public int WhatNumber()
{
//Access inside the class is possible
return RightNumber();
}
}

//MySubClass is only visible from this library
internal class MySubClass : MyClass
{
int AnotherRightNumber()
{
//Works
b = 8;
//Does not work – a cannot be accessed since it is private
return a;
}
}