add a getter to a class in csharp

To add a getter to a class in C#, you can define a property with a get accessor. Here's an example:

main.cs
public class Person
{
    private string name;

    public string Name
    {
        get { return name; }
    }
}
114 chars
10 lines

In this example, Person is a class with a private field name. The Name property has a get accessor, which returns the value of the name field.

To use this getter, you can create an instance of the Person class and access the Name property:

main.cs
Person person = new Person();
person.Name = "Alice"; // This will cause a compiler error, because the Name property doesn't have a set accessor.
string name = person.Name; // This will return "Alice".
201 chars
4 lines

Note that because the Name property doesn't have a set accessor, you can't change the value of name directly, making it an example of encapsulation.

gistlibby LogSnag