Thuta Learning
IntermediateProgrammingbeginner

Properties

Relax. We'll talk through this in plain words — no textbook voice.

Properties are used to safely access private data. Instead of making a field directly public, you control access through get / set, which also makes it easy to add validation logic.

csharp
class Person
{
    private string name;

    public string Name
    {
        get { return name; }
        set
        {
            if (!string.IsNullOrWhiteSpace(value))
            {
                name = value;
            }
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person();
        person.Name = "Liam";
        Console.WriteLine(person.Name);
    }
}

What to take away from this code

  • name field is private, so it can't be changed directly from outside the class.
  • Name property controls and provides access to that data.
  • set checks against an empty string being set.
You should see
Liam