Looking for a short & simple example of getters/setters in C#
Categories:
Understanding Getters and Setters in C#

Explore the fundamentals of properties in C# with simple examples, covering automatic, full, and expression-bodied properties.
In C#, getters and setters are fundamental components of properties, which provide a flexible and controlled way to access and modify an object's private fields. They encapsulate data, allowing you to add validation logic, logging, or other operations whenever a field is read or written. This article will provide a concise and clear explanation of how to use getters and setters in C#, demonstrating various property syntaxes.
The Basics: What are Getters and Setters?
At their core, getters and setters are special methods that allow you to retrieve (get) and assign (set) values to private fields within a class. While you could write public methods like GetValue()
and SetValue()
, C# properties offer a more elegant and idiomatic syntax. They make your code cleaner, more readable, and enforce encapsulation by controlling how data is accessed.
classDiagram class Person { -string _name +string Name +int Age +void Greet() } Person : +string getName() Person : +void setName(string name) Person --> Name : uses Person --> Age : uses
Conceptual class diagram showing how properties (Name, Age) interact with internal fields (like _name) via getters and setters.
Automatic Properties (C# 3.0+)
The simplest way to define a property in C# is using an automatic property. This syntax is a shorthand when no additional logic is required in the getter or setter. The compiler automatically generates a private backing field for you. This is ideal for simple data storage.
public class Product
{
// Automatic property
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; private set; } // Setter is private
public Product(int id, string name, decimal price)
{
Id = id;
Name = name;
Price = price;
}
}
// Usage:
Product laptop = new Product(101, "Gaming Laptop", 1200.00m);
Console.WriteLine($"Product: {laptop.Name}, ID: {laptop.Id}, Price: {laptop.Price}");
// laptop.Price = 1300.00m; // This would cause a compile-time error because the setter is private
Example of automatic properties in a Product
class.
Full Properties (with Backing Field)
When you need to add custom logic, such as validation, logging, or transformation, to either the getter or the setter, you use a full property. This involves explicitly declaring a private backing field and then defining the get
and set
accessors to interact with that field.
public class Employee
{
private string _employeeName; // Private backing field
private decimal _salary;
public string EmployeeName
{
get { return _employeeName; }
set
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("Employee name cannot be empty.");
}
_employeeName = value.Trim(); // Trim whitespace
}
}
public decimal Salary
{
get { return _salary; }
set
{
if (value < 0)
{
Console.WriteLine("Warning: Salary cannot be negative. Setting to 0.");
_salary = 0;
}
else
{
_salary = value;
}
}
}
public Employee(string name, decimal salary)
{
EmployeeName = name; // Uses the setter logic
Salary = salary; // Uses the setter logic
}
}
// Usage:
Employee emp = new Employee(" Alice Smith ", 50000m);
Console.WriteLine($"Employee: {emp.EmployeeName}, Salary: {emp.Salary}");
try
{
emp.EmployeeName = ""; // This will throw an exception
}
catch (ArgumentException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
emp.Salary = -1000m; // This will trigger the warning and set salary to 0
Console.WriteLine($"Employee: {emp.EmployeeName}, New Salary: {emp.Salary}");
Example of full properties with custom logic for validation and transformation.
Expression-Bodied Properties (C# 6.0+)
For properties where the getter or setter logic is a single expression, C# offers expression-bodied members. This provides a more concise syntax, especially useful for read-only properties or simple calculations.
public class Circle
{
public double Radius { get; set; }
// Expression-bodied property for Area (read-only)
public double Area => Math.PI * Radius * Radius;
// Expression-bodied property with a setter (less common, but possible)
private string _color;
public string Color
{
get => _color;
set => _color = value ?? "Unknown"; // Null-coalescing assignment
}
public Circle(double radius, string color)
{
Radius = radius;
Color = color;
}
}
// Usage:
Circle myCircle = new Circle(5.0, "Blue");
Console.WriteLine($"Circle Radius: {myCircle.Radius}, Area: {myCircle.Area:F2}, Color: {myCircle.Color}");
myCircle.Color = null;
Console.WriteLine($"Circle Color after null assignment: {myCircle.Color}");
Example of expression-bodied properties for calculated values and simple assignments.