Access Modifiers

This article explains access modifiers and their functionality, along with how they differ from each other and what the basics of all these are.

I'll include all 4 access modifiers in this article.

Access Modifiers in C#

Class Access Modifiers | C#

I will explain this with an example.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Hello_Word

{

class Program

{

static void Main(string[] args)

public int Value;

// public access modifier

private string Message;

// private access modifier

protected void function();

// protected access modifier

}

}

We can use any of the class modifiers in our class but each of these modifiers work differently.

Modifiers | Types

Modifiers

Public

The public modifier specifies that the class's values and attributes can be easily accessed by other objects.

Private

The private access modifier is for when the functionality of an attribute of that class can be only used within that class only.

Protected

Internal

Example

There are 2 parts in this code, the first part represents construction building and access modifier definitions. In the second code there is a calling of the access modifiers functionalities.

Part: 1 | Code

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Hello_Word

{

class Book

{

// access modifier- PUBLIC

public string Name;

public decimal Price;

public string Description;

// access modifier- PRIVATE

private decimal discount;

// public constructer

public Book(string bookName, decimal price)

{

Name = bookName;

Price = price;

discount = 0.0m;

}

}

}


Part: 2 | Code

class Program

{

static void Main(string[] args)

{

Book b1 = new Book("Black Book", 1050.00m);

Book b2 = new Book("Complete Refrence", 1250.00m);

string str = b1.Name;

}
}

When you do try to define b1.discount then there will be no option in the list as:

discount

It only shows the list of members of that class declared under Public access modifier.

Public access modifier

But if you do try to declare it then it will show an error like this:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Hello_Word

{

class Program

{

static void Main(string[] args)

{

Book b1 = new Book("Black Book", 1050.00m);

Book b2 = new Book("Complete Refrence", 1250.00m);

string str = b1.Name;

decimal dsc = b2.discount;

}

}

}

// We can not directly use discount in our next file, because it is defined under a private class, we didn't get the options from the list but if we do try to do so, it will surely show an error as in the following:

"Inaccessible due to private modifier"

Inaccessible due to private modifier

The same in the case of a protected modifier, if you try to access its properties it will again show the same message:

message