• Startseite
  • Tutorials
  • Kontakt
  • Mein Account
Panjutorials
  • Startseite
  • Tutorials
  • Kontakt
  • Mein Account

Access modifier in CSharp

In one of the first CSharp articles, I briefly discussed Private, Public, Internal and Protected. Since it is not easy at first to understand the meaning behind these different access types, I will now go into it more precisely.

First of all, basic conventions:

Variables are declared with private
Functions are declared with public
Now you might think we had already seen something different. That’s true. You can also declare  functions private and variables public. If you declare a function private, it cannot be used from other classes. So if you have a function  functionA in the class A and want to call it from class B, you cannot do this if the function is set to private. This can only be done if the function is public.

Variables have the same behavior. We had already dealt with the fact that setters and getters are needed to change a variableA of classA in the class B. That’s not quite right. If you declare the variableA public you can invoke it from classB as follows:

public class KlasseA {
	public int var1 = 3;
}
public class KlasseB {	

	public static void Main(string[] args) {
		ClasseA classAObject = new classA();
		classAObject.var1 = 5;

		Console.WriteLine(classAObject.var1);
                Console.Read();
	}

}

There are four types of access modifiers:

Private

If a variable or function is declared private, then it is only visible in the class in which it was created, so not by other classes.

Public

If a variable or function is declared public, it is visible and editable from any class that has a reference (object) to the class of the variable / function.

Internal

Access is limited to the current assembly

Protected internal: access is restricted to the current assembly or to types derived from the class.

Protected

If a variable or  function is declared protected, then only the same package, or classes inheriting from the class of the variable / function, can be accessed from it. What inheritance means, or inheritance is, will be covered in a later article.