C# Basics – Access Modifiers

The second installment in my series of C# basics illustrates the proper use of access modifiers.

The public access modifier is the least desirable because it allows access to its members from anywhere in the program.


class Employee2

{
    // These private members can only be accessed from within this class or any classes that inherit this class
    private string name = "FirstName, LastName";

    private double salary = 100.0;

    // The application can still access the value of these members, by way of these public methods
    public string GetName()
    {
        return name;

    }

    // This public method ensures that salary is read only (there's no set{}) methods
    public double Salary
    {
        get { return salary; }
    }
}
class PrivateTest
{
    static void Main()
    {

        Employee2 e = new Employee2();

        // Since 'name' and 'salary' are private in the Employee2  class:
        // they can't be accessed like this:
        //    string n = e.name;

        //    double s = e.salary;

        // 'name' is indirectly accessed via method:

        string n = e.GetName();

        // 'salary' is indirectly accessed via property
        double s = e.Salary;
    }

}



Posted in C#

Question or comment?