add a property to a class in csharp

To add a property to a class in C#, you can use the get and set accessors within the class definition. Here's an example:

main.cs
public class Person
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}
144 chars
11 lines

In this example, we've defined a Person class with a private name field and a public Name property. The get accessor returns the value of name, while the set accessor sets the value of name to whatever value is passed in.

You can access the Name property just like any other field or property of the Person class:

main.cs
Person person = new Person();
person.Name = "John";
string name = person.Name; // "John"
89 chars
4 lines

related categories

gistlibby LogSnag