C# Properties
Learn C# through interactive, bite-sized lessons. Build .NET applications with hands-on practice.
Start C# Journey →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.
Basic Syntax
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.
Auto-Implemented Properties
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.
Read-Only and Write-Only Properties
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
Property Usage Example
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)
Benefits of Using Properties
- Encapsulation: Properties provide a way to access private fields, maintaining data integrity.
- Flexibility: You can easily add validation or computation logic without changing the public interface.
- Readability: Properties make the code more intuitive and self-documenting.
Best Practices
- Use properties instead of public fields to ensure better encapsulation.
- Keep property accessors simple. For complex logic, consider using methods instead.
- Use auto-implemented properties when no additional logic is required in the accessors.
- Consider making properties read-only when they should not be modified externally.
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#.
Advanced Property Features
C# also supports more advanced property features, such as:
- Expression-bodied properties (for simple get-only properties)
- Computed properties
- Properties with different access levels for get and set accessors
These features enhance the flexibility and power of properties in C#, making them an essential tool for every C# developer.