What are Property Accessors?
What are Property Accessors?
Property accessors in C# are special methods that provide a way to control how a property's value is accessed or modified. They allow you to add custom logic when getting or setting the value of a property. There are two types of property accessors:
Here's an example of a property with both get and set accessors:
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
In this example, the Name
property has a private backing field _name
. The get
accessor returns the value of _name
, while the set
accessor assigns the value passed to it (represented by the value
keyword) to _name
.
You can also add custom logic inside the accessors. For example, you can perform validation or transformation of the value being set:
private int _age;
public int Age
{
get { return _age; }
set
{
if (value < 0)
...
entry
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào