Câu hỏi phỏng vấn C#
Câu hỏi

What are Property Accessors?

Câu trả lời

Property Accessors in C#

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:

  1. get accessor: This accessor is used to retrieve the value of a property.
  2. set accessor: This accessor is used to assign a value to a property.

Here's an example of a property with both get and set accessors:

csharp Copy
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:

csharp Copy
private int _age;

public int Age
{
    get { return _age; }
    set
    {
        if (value < 0)
       ...
entry

entry

Gợi ý câu hỏi phỏng vấn

middle

Explain assignment vs shallow copy vs deep copy for a Record in C#

middle

What is the difference between Virtual method and Abstract method?

senior

What is the difference between System.ApplicationException class and System.SystemException class?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào