add a private property to a class in csharp

To add a private property to a class in C#, you can declare a private field within the class, and then create a public property that encapsulates this private field using getter and setter methods.

Here is an example:

main.cs
public class MyClass 
{
    private string _myPrivateProperty;

    public string MyPublicProperty 
    {
        get { return _myPrivateProperty; }
        set { _myPrivateProperty = value; }
    }
}
201 chars
11 lines

In this example, we declare a private field called _myPrivateProperty within the MyClass class. We then create a public property called MyPublicProperty that allows external code to access and modify this private field.

The get method retrieves the value of _myPrivateProperty, while the set method sets its value to the parameter passed in. By encapsulating the private field within a public property, we provide controlled access to the data, enforcing encapsulation and ensuring that the data is accessed and modified in a safe and consistent way.

gistlibby LogSnag