Поделиться через


public (C# Reference)

The public keyword is an access modifier for types and type members. Public access is the most permissive access level. There are no restrictions on accessing public members, as in this example:

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

See Access Modifiers (C# Programming Guide) and Accessibility Levels (C# Reference) for more information.

Example

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

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

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

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

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

C# Language Specification

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

See Also

Reference

Access Modifiers (C# Programming Guide)

C# Keywords

Access Modifiers (C# Reference)

Accessibility Levels (C# Reference)

Modifiers (C# Reference)

private (C# Reference)

protected (C# Reference)

internal (C# Reference)

Concepts

C# Programming Guide

Other Resources

C# Reference