Properties in C# provide a flexible mechanism to read, write or compute the values of private fields. They are special methods called accessors that control access to class data.
class Person
{
private string name; // private field
// Property for name with get and set accessors
public string Name
{
get { return name; }
set { name = value; }
}
}
If no extra logic is needed, you can use auto-properties which let the compiler create the hidden backing field automatically:
class Person
{
public string Name { get; set; } // auto-implemented property
}
get
accessor.set
accessor (rarely used).
class Person
{
public string Name { get; } // read-only
public Person(string name)
{
Name = name; // can set only inside constructor
}
}
class Person
{
private int age;
public int Age
{
get { return age; }
set
{
if (value >= 0) // validate age
age = value;
else
throw new ArgumentException("Age cannot be negative");
}
}
}
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!