add a public property to a class in csharp

To add a public property to a class in C#, you can use the encapsulation mechanism which involves defining private variables in the class and then providing public getters and setters to access and modify those variables.

Here's an example of a class with a public property:

main.cs
public class Person
{
    // private variables to store the data
    private string _firstName;
    private string _lastName;

    // public properties to access the data
    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }
    
    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }
}
397 chars
20 lines

In the above example, the Person class has two private variables, _firstName and _lastName, which store the first and last names of a person. The class also has two public properties, FirstName and LastName, which allow other code to access and modify the values of those private variables.

The get accessor retrieves the value of the private variable, and the set accessor sets the value of the private variable. By making the properties public, other code can read and update the values of the private variables without directly accessing them. This helps to encapsulate the implementation details of the class and provide a clean interface for other code to use.

gistlibby LogSnag