📜  c# on variable change property get set - C# (1)

📅  最后修改于: 2023-12-03 15:13:49.406000             🧑  作者: Mango

C# on Variable Change Property Get Set

In C#, a property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors.

One of the useful features of properties is the ability to execute code when a property value is changed. This can be done using a combination of both the get and set accessors.

To demonstrate this, let's create a class called Person with two properties: FirstName and LastName.

public class Person
{
    private string firstName;
    private string lastName;

    public string FirstName
    {
        get { return firstName; }
        set
        {
            firstName = value;
            Console.WriteLine("First name has been changed to: " + value);
        }
    }
    
    public string LastName
    {
        get { return lastName; }
        set
        {
            lastName = value;
            Console.WriteLine("Last name has been changed to: " + value);
        }
    }
}

In this example, both the FirstName and LastName properties have a get accessor and a set accessor. In the set accessor, we are setting the value of the private field and then printing a message to the console indicating that the value has been changed.

We can now create an instance of the Person class and set the properties.

Person person = new Person();
person.FirstName = "John";
person.LastName = "Doe";

When we set the value of each property, the message will be printed out to the console.

>> First name has been changed to: John
>> Last name has been changed to: Doe

This is just a simple example, but it demonstrates the power of using properties to execute code when a value is changed. This can be useful in many scenarios, such as validating input, updating user interfaces, or triggering other actions.

In summary, C# properties provide a useful mechanism to read, write, or compute the value of private fields. By using the get and set accessors, we can execute code when a property value is changed, providing more flexibility in our code.