- public is the most common access specifier in C#.
- It can be access from anywhere, that means there is no restriction on accessibility.
- The scope of the accessibility is inside class as well as outside.
- The type or member can be accessed by any other code in the same assembly or another assembly that references it.
There are no restrictions on accessing public members.
Accessibility:
- Can be accessed by objects of the class
- Can be accessed by derived classes
Example:
namespace MyApp1
{
class access
{
// String Variable declared as public
public string name;
// Print method declared as public
public void print()
{
Console.WriteLine("\nHi, My name is " + name);
}
}
class Program
{
static void Main(string[] args)
{
access objaccess = new access();
Console.Write("Enter your name:\t");
// Accepting value in public variable that is outside the class
objaccess.name = Console.ReadLine();
objaccess.print();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Enter your name: Rejin
Hi, My name is Rejin