CSharp - Create a write only property

Introduction

The properties that have only set accessors are called write-only properties.

The following is an example of a write-only property:

private int myInt;
public int MyInt
{
           //get accessor is absent here
          set
          {
              myInt = value;
          }
}

Demo

using System;
class MyClass/*  ww  w  .j  a  va2s  . c  o  m*/
{
    private int myInt; // also called private "backing" field
    public int MyInt   // The public property
    {
        set
        {

            if ((value >= 10) && (value <= 25))
            {
                myInt = value;
            }
            else
            {
                Console.WriteLine("The new value {0} cannot be set", value);
                Console.WriteLine("Please choose a value between 10 and 25");
            }
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        MyClass ob = new MyClass();
        ob.MyInt = 10;
        ob.MyInt = 100;
    }
}

Result

Related Topic