What are Properties in C#? Explain with an example.
Short answer
Properties in C# are members that provide a flexible way to read, write, or compute the value of a private field while still exposing that access through a simple, field like syntax.
Advertisement
AModel answer
Properties in C# are members that provide a flexible way to read, write, or compute the value of a private field while still exposing that access through a simple, field like syntax. A property typically consists of a get accessor for reading the value and a set accessor for writing it, allowing you to add validation logic or computed behavior behind the scenes without changing how the property is used from outside the class.
public class Person {
private int _age;
public int Age {
get { return _age; }
set {
if (value < 0) throw new ArgumentException("Age cannot be negative");
_age = value;
}
}
}Real-world example
A Person class exposes an Age property that silently validates any value being assigned to it, rejecting negative numbers, so any code that sets a person's age automatically benefits from this protection without needing to call a separate validation method.
Likely follow-ups
- What is the difference between a field and a property in C#?
- Can a property have only a getter and no setter?
Related topics