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
namefield is private, so it can't be changed directly from outside the class.Nameproperty controls and provides access to that data.setchecks against an empty string being set.
You should see
Liam