Επεξεργασία

Κοινοποίηση μέσω


public (C# reference)

Use the public keyword as an access modifier for types and type members. Public access is the most permissive access level. The following example shows that you can access public members without any restrictions:

class SampleClass
{
    public int x; // No access restrictions.
}

For more information, see Access Modifiers and Accessibility Levels.

The C# language reference documents the most recently released version of the C# language. It also contains initial documentation for features in public previews for the upcoming language release.

The documentation identifies any feature first introduced in the last three versions of the language or in current public previews.

Tip

To find when a feature was first introduced in C#, consult the article on the C# language version history.

In the following example, two classes are declared, PointTest and Program. The public members x and y of PointTest are accessed directly from Program.

class PointTest
{
    public int x;
    public int y;
}

class Program
{
    static void Main()
    {
        var p = new PointTest();
        // Direct access to public members.
        p.x = 10;
        p.y = 15;
        Console.WriteLine($"x = {p.x}, y = {p.y}");
    }
}
// Output: x = 10, y = 15

If you change the public access level to private or protected, you get the error message:

'PointTest.y' is inaccessible due to its protection level.

C# language specification

For more information, see Declared accessibility in the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See also