Share via


Error: The modifier 'readonly' is not valid for this item

Question

Friday, January 12, 2018 7:29 AM

I want to ask you that why above error comes in below code. Thanks in advance.

using System;
class ConstantDemo
{
 static void Main()
 {
  //const int i=3;
  readonly bool flag;
  flag=true;
 }
}

All replies (2)

Friday, January 12, 2018 8:11 AM âś…Answered | 1 vote

The readonly modifier can only be applied to fields, not local variables within a method. E.g

class Program
{
    static readonly bool flag = false;

    static void Main(string[] args)
    {
    }

}

Furthermore they can only be assigned in the declaration (as I am doing above) or in the class constructor. 


Saturday, January 13, 2018 3:32 AM

Ok. Thank you.

  • Readonly can be declared only at class level not inside the method.