When you define a class, you have to decide who will have the permission. Here we find the access modifiers, which are reserved keywords used for specifying the access level. The way they are used is:
[access modifier] element ...The access modifiers are avalaible for most of the elements in the C# language: fields, methods, arrays, etc., even the classes.
This is the first you will see. With this modifier, you are giving anyone the permission for accessing your element. For example, lets remember our MyClass class:
public int GetResult ( int n ) ...Note the public word. So, any element outside of the class will be able to work with it. Actually, a good class design will never make public any field, and you should avoid it, making public other elements, such your methods. If you want to access your fields, do it throughout a property.
With private, you will guarantee that your elements wont'be avalaible for any extern element. In fact, they are only avalaible for your intern elements. This is how you should declare your fields. An example would be:
private int MyField;Note that our MyField field was declared as private. If, for example, you try to access it, then you'll get an compilation error message. By the way, the default access modifier for the elements in a class ( this is, when you don't put any access modifier to a specified element ) is private.
When you derive a class ( this is, you have a general class and want another one to inherit its elements and add some more specific ), if you previous elements were defined as private, you won't be able to access them. To solve this problem, we use the protected modifier:
// Our general class class GeneralClass { private int a; protected int b; } // Our extended class class ExtendedClass : GeneralClass { // Let's modify the fields in the constructor this.a = 10; // Error ! this.b = 10; // perfect! }if you don't understand very well the inheritance, don't worry, only try to see this as if you understand this, and after the inheritance section, go back to understand perfect this modifier.