C# – Access Modifiers – public access modifier

We have discussed access modifiers or access specifiers in our previous article “C# – Access Modifiers“. In this article, I am going to explain in more detail about “public access modifier” with examples.

public Access Modifier

The modifier allows all the class members and the class itself to access outside the Assembly,  Namespace, or outside of a class. Usually, when we define structures in C#, we make all its’ members accessible to everyone.

We use “public” keyword to define public member; which allows accessing the member to everyone.

In an Assembly (.exe or .dll file):

All the defined public members in a class can be accessed within the class and outside of the class.

public classes defined in a namespace can be accessible within the namespace and in another namespace.

From another Assembly (.exe or .dll file):

The public members defined in one Assembly can be accessible from another Assembly.

Before using public members of an Assembly you must add as a Reference

Lets’ put it all together in programs and verify how we can access public members within the assembly, within the namespace, and within the class.

Lets’ define a namespace & a class with public members in an Assembly. Define a public class in a namespace & print the message, when its’ object has been created.

Press any key to continue . . .

When you run the program, observe that it calls the PublicClass constructor to display the message.

Lets’ define another namespace & a class; in another Assembly and try to access the public members from the previously defined Assembly. To access the member of a class from another Assembly; you must first add the Assembly as a reference in another Assembly. And to use the Assembly members use the keyword “using“.

The below program has complete code:

Press any key to continue . . .

When you Run this program; observe that, Assembly2 calls the Assembly1 members, and results were shown.


C# – Access Modifiers – public access modifier

Leave a Reply

Your email address will not be published.

Scroll to top