C# properties are members of classes, structures, and interfaces that provide a flexible mechanism to read, write, or compute the values of private fields. They are an essential part of encapsulation in object-oriented programming. This guide explains everything about properties in C# from basic usage to advanced features.
In C#, a property is a class member that encapsulates a getter and/or a setter method. Instead of accessing the fields directly, properties allow for access control and abstraction by providing a controlled interface to the internal data of a class.
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
Here, Age is a property with a private backing field _age. The get accessor returns the value, and the set accessor assigns a value.
public string Name { get; set; }
This is an auto-implemented property that provides both get and set accessors.
private string _id = Guid.NewGuid().ToString();
public string Id
{
get { return _id; }
}
Only a get accessor is provided, making this a read-only property.
private string _password;
public string Password
{
set { _password = value; }
}
This kind of property is rare. It allows writing but not reading the value.
public int Age { get; set; }
C# allows shorthand syntax for properties with no additional logic in accessors.
A backing field is a private variable that stores the actual data. It is accessed and manipulated through property accessors.
private int _age;
public int Age
{
get { return _age; }
set
{
if (value > 0)
_age = value;
}
}
In this example, the setter validates that age must be positive.
Used to return the property value. Required for reading the property.
Used to assign a new value. The keyword value represents the value being assigned.
Accessors can have different access levels than the property itself:
public string Secret
{
get;
private set;
}
Here, the property is publicly readable but privately writable.
public class Rectangle
{
public int Width { get; set; }
public int Height { get; set; }
public int Area
{
get { return Width * Height; }
}
}
Area is a computed property whose value is calculated on-the-fly and not stored.
Introduced in C# 6, you can use lambda-like syntax:
public int Area => Width * Height;
This syntax is useful for simple get-only properties.
public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}
init makes a property settable only during object initialization.
var person = new Person { FirstName = "John", LastName = "Doe" };
Like static methods, static properties belong to the type, not instances.
public class Counter
{
private static int _count = 0;
public static int Count
{
get { return _count; }
set { _count = value; }
}
}
Interfaces can define property signatures:
public interface IShape
{
int Area { get; }
}
Classes implementing the interface must implement the property.
public class Animal
{
public virtual string Sound { get; set; }
}
Derived classes can override virtual properties.
public class Dog : Animal
{
public override string Sound { get; set; } = "Bark";
}
public abstract class Shape
{
public abstract int Area { get; }
}
Must be overridden by derived classes.
private int _score;
public int Score
{
get { return _score; }
set
{
if (value >= 0)
_score = value;
else
throw new ArgumentOutOfRangeException("Score cannot be negative.");
}
}
This property validates that score must be non-negative.
Properties are critical in frameworks like WPF or WinForms for data binding. They often work with the INotifyPropertyChanged interface.
public class Person : INotifyPropertyChanged
{
private string name;
public string Name
{
get => name;
set
{
name = value;
OnPropertyChanged(nameof(Name));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Properties are slightly slower than fields due to method calls (getter/setter), but they are the recommended approach for most cases. If raw performance is needed (e.g., game engines), fields might be used with caution.
| Aspect | Field | Property |
|---|---|---|
| Encapsulation | None | Supports encapsulation |
| Data Binding | Not supported | Supported |
| Inheritance Support | No | Yes |
| Validation | Not possible | Possible |
C# properties provide an elegant and powerful way to encapsulate data. They form a bridge between private fields and the public API of a class, allowing for control, validation, and flexibility. Understanding properties is essential for writing clean, maintainable, and object-oriented C# code. Whether you're working with UI frameworks, writing business logic, or designing libraries, properties are indispensable tools in your toolkit.
C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved