Friday, May 12, 2023

Property or properties in C#

 What is Property in C#?


In C#, a property is a member of a class that encapsulates a private field and provides a way to read or write its value. Properties provide a more controlled way to access and modify the data within a class than simply exposing the private field directly.


A property is defined using a combination of a get accessor and/or a set accessor. The get accessor returns the value of the property, while the set accessor assigns a new value to the property.


Here's an example of a property:



public class clsPerson

{

    private string name;


    public string Name

    {

        get { return name; }

        set { name = value; }

    }

}



In this example, the "clsPerson" class has a private field called "name", which is encapsulated by a public property called "Name". The get accessor returns the value of the "name" field, while the set accessor assigns a new value to the field.


Properties can also have additional logic within their accessors to enforce constraints or perform other actions when the property is read or written. Here's an example of a property with additional logic:



public class clsBankAccount

{

    private decimal balance;


    public decimal Balance

    {

        get { return balance; }

        set

        {

            if (value < 0)

            {

                throw new ArgumentException("Balance cannot be negative");

            }

            balance = value;

        }

    }

}



In this example, the "clsBankAccount" class has a private field called "balance", which is encapsulated by a public property called "Balance". The set accessor includes a check to ensure that the value being assigned to the property is not negative. If the value is negative, an exception is thrown. This ensures that the balance of the bank account is always non-negative.

No comments:

Post a Comment

If you have any query kindly let me know.

Blazor drawback| drawback of blazor| Disadvantage of blazor in c#

  Blazor drawback| drawback of blazor| Disadvantage of blazor in c# While Blazor offers many advantages, it also has a few drawbacks to cons...