Understanding the 'public' Access Modifier in C#

C# public Keyword

The public keyword is an access modifier used to define the visibility and accessibility of classes, methods, properties, fields, and other members within a program. When a class or member is marked as public, it can be accessed from any code within the program, both inside and outside of the defining class or assembly.

Here's how you can use the public keyword:

Public Class:

public class ExampleClass
{
    // Class members and methods go here.
}

In this example, ExampleClass is marked as public, allowing it to be accessed from any part of the program.

Public Method:

public void DisplayMessage()
{
    Console.WriteLine("Hello, World!");
}

In this example, DisplayMessage method is marked as public, making it accessible from anywhere in the program.

Public Property:

public string Name { get; set; }

In this example, Name property is marked as public, allowing it to be read from or written to from any code within the program.

The public access modifier is commonly used when you want to expose a class or its members to other parts of the code, enabling interaction with the class's functionality from various places within the application or even from other assemblies. It provides a way to create public interfaces for your classes, making them accessible and usable by other parts of your program.