Properties in C#

Properties in C# is a member that provides  a flexible work to write, read or compute a value of a private field. Properties is one or two code blocks and representing a get and set accessor. For get accessor the code block executed when the property is read and for the set executed when the property is assigned a new value. Set property is only for reading and get property considered write – only.

Defining Properties

  • Properties are like data fields, but have a logic behind them
  • From the outside, they look like any other member variable
  • Defined like a fiel, with “get” and “set” code addedd
  • Can use access modifiers like fields and methods can

class mExample
{
    private int mValue; // private data field

    public int Value
    {

       get { return mValue; }

       set { mValue = value; } // value is implicit
        
    }
           
}


















Read-Only

 class mExample
 {
   private int mValue;
   //read-only property
   public int Value
   {
      get { return mValue; }
   }

  }


















Write-Only
class mExample
{
   private int mValue;
   //Write-only property
   public int Value
   {
      set { mValue = value; }
   }


}

No comments:

Post a Comment