CSharp - Create a read only property

Introduction

We have only get an accessor, it is known as a read-only property.

The following is a read-only property:

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

Demo

using System;
class MyClass/*  ww  w .  ja v a2 s.  c  o  m*/
{
    private int myInt; // also called private "backing" field
    public int MyInt   // The public property
    {
        get
        {
            return myInt;
        }

    }
}
class Program
{
    static void Main(string[] args)
    {
        MyClass ob = new MyClass();
        Console.WriteLine("\nValue of myInt is now:{0}", ob.MyInt);
    }
}

Result

Related Topic