Properties in C# are a powerful feature that provide a flexible mechanism to read, write, or compute the values of private fields. They offer a level of abstraction, allowing you to change the internal implementation without affecting the public interface.
The basic syntax of a property in C# is as follows:
public Type PropertyName
{
get { return field; }
set { field = value; }
}
Here, get
and set
are called accessors. The get
accessor returns the property value, while the set
accessor assigns a new value.
C# also supports auto-implemented properties, which provide a concise way to declare properties:
public Type PropertyName { get; set; }
This syntax automatically creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
Properties can be made read-only or write-only by omitting the set or get accessor, respectively:
public string Name { get; } // Read-only property
public int Age { private get; set; } // Write-only property
Let's look at a practical example of using properties in a C# class:
public class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public int Age { get; set; }
public string FullName => $"{Name} (Age: {Age})";
}
// Usage
Person person = new Person();
person.Name = "John Doe";
person.Age = 30;
Console.WriteLine(person.FullName); // Output: John Doe (Age: 30)
Properties are closely related to C# encapsulation and play a crucial role in object-oriented programming. They provide a clean way to implement inheritance and support polymorphism in C#.
C# also supports more advanced property features, such as:
These features enhance the flexibility and power of properties in C#, making them an essential tool for every C# developer.