Wednesday, October 7, 2015

Modify the value of readonly varibale

Modify the value of readonly varibale

Concert crowd

The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

This is how we declare a readonly variable:

  1: public readonly int objreadonly = 100;

You can only change the value of a readonly variable at the constructor level of the same class.

An Excerpt about readonly is :

A readonly field can only be set upon field initialization or in a constructor. This gives considerable benefit for ongoing maintenance because you can ensure it was set when the object was created and not modified since. Though there is no performance benefit.

I have used a little practical demonstarion of this.

  1: class Readonly
  3:     {
  4: public readonly int objreadonly = 100;
  5:         Readonly()
  6:         {
  7:         }
  8: public void  ChangeValueofReadonly()
  9:         {
 10:             objreadonly = 200;
 11:         }
 12:     }
 13: class Program
 14:     {
 15: static void Main(string[] args)
 16:         {
 17:         }
 18:     }
If you notice I tried to change the value of readonly object "objreadonly" but I'm not successful at changing its value, it issues the error "A readonly field cannot be assigned to (except in a constructor or a variable initializer)" also depicted below in the snap shot.


In other words you can't change its value at method level at class level. It can change at constructor level only.

Let's do it :


This is a small demonstration that I hope will help you somewhere down the line


Post a Comment