C# Keywords Tutorial Part 67: public

C# Keywords Tutorial Part 67: public

The “public” keyword in C# is used to specify the accessibility of a class member or type. When a member or type is marked as public, it can be accessed from any code that has access to the class or type. This keyword is an important part of encapsulation in object-oriented programming, as it determines which parts of the class are visible to the outside world.

Let’s take a look at some code examples to understand how the “public” keyword works.

Example 1: Public Class

public class MyClass
{
    public int MyPublicProperty { get; set; }
    private int MyPrivateProperty { get; set; }
    
    public void MyPublicMethod()
    {
        // Code here
    }
    
    private void MyPrivateMethod()
    {
        // Code here
    }
}

In this example, we have a class named “MyClass” that contains two properties and two methods. The first property, “MyPublicProperty,” is marked as public, which means it can be accessed from any code that has access to the class. The second property, “MyPrivateProperty,” is marked as private, which means it can only be accessed from within the class itself. Similarly, the first method, “MyPublicMethod,” is marked as public, while the second method, “MyPrivateMethod,” is marked as private.

Example 2: Public Constructor

public class MyClass
{
    public MyClass()
    {
        // Code here
    }
}

In this example, we have a class named “MyClass” that contains a public constructor. A constructor is a special method that is called when an instance of a class is created. By marking the constructor as public, we allow other code to create instances of the class.

Example 3: Public Interface

public interface IMyInterface
{
    void MyMethod();
}

In this example, we have an interface named “IMyInterface” that contains a single method. An interface defines a contract that a class can implement. By marking the interface as public, we allow other code to use it as a type.

Example 4: Public Enum

public enum MyEnum
{
    Value1,
    Value2,
    Value3
}

In this example, we have an enum named “MyEnum” that contains three values. An enum is a type that consists of a set of named values. By marking the enum as public, we allow other code to use it as a type.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *