Types Of Property In C#

In C#, there are three types of properties that can be defined:

1. Read-write Properties:

These properties allow both read and write operations on the data members of a class. They can be defined using the get and set accessors. For example:

public string Name
{
    get { return _name; }
    set { _name = value; }
}

In this example, Name is a read-write property that allows getting and setting the _name field.

2. Read-only Properties:

These properties allow only read operations on the data members of a class. They can be defined using only the get accessor. For example:

public string FullName
{
    get { return $"{FirstName} {LastName}"; }
}

In this example, FullName is a read-only property that allows only getting the value of the concatenation of FirstName and LastName fields.

3. Write-only Properties:

These properties allow only write operations on the data members of a class. They can be defined using only the set accessor. However, such properties are not commonly used because they cannot be accessed for reading. For example:

public string Password
{
    set { _password = Encrypt(value); }
}

In this example, Password is a write-only property that allows only setting the value of the _password field. Note that the get accessor is not defined for this property.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories