Categories: C#

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;
    }

}



Rick Bishop

Share
Published by
Rick Bishop

Recent Posts

C# System.Uri Class Examples

If you've needed to parse or construct a URI in C#, you've likely done it…

6 years ago

C# Coding Style

This page details the coding style I've adopted for C# code in my applications. You…

6 years ago

C# Basics – Inheritance

For the new C# section of my website, I wanted to post some notes that…

6 years ago

5 Reasons to Lock Down Your LinkedIn Profile

There are some pretty compelling reasons to lock down your LinkedIn account now. We bet…

6 years ago

LinkedIn is Ignoring Your Privacy Settings and You Paid Them to Do It

We bet you didn't know that your full name, picture, work history, and more may…

6 years ago

In Review: C# 7.0 in a Nutshell

I've always been a huge fan of O'Reilly's "In a Nutshell" series. C# in a…

6 years ago