Modify the Value of Readonly Varibale

Modify the value of readonly varibale

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:

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.

class Readonly

    {
        public readonly int objreadonly = 100;

        Readonly()

        {
 
        }

        public void  ChangeValueofReadonly()

        {

            objreadonly = 200;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

        }

    }

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.

Readonly-variable-in-Csharp.jpg

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 :

Readonly-variable.jpg

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