3
Answers

Error: Invalid token '=' in class, struct, or interface memb

Dinesh Kudale

Dinesh Kudale

7y
139
1

Why above error is coming after the compilation of this code. Thanks in advance.

-----------------------------------------------------------------------------------------------------

using System;
class ReadonlyDemo
{
readonly bool flag;
flag=true;
static void Main()
{
}
}

Answers (3)
2
Manav Pandya

Manav Pandya

NA 7.1k 24k 7y
Hello
 
You should do like this :
 
  1. class Program  
  2.     {  
  3.         readonly bool flag ;  
  4.         Program()  
  5.         {  
  6.             flag = true;  
  7.         }  
  8.           
  9.         static void Main(string[] args)  
  10.         {  
  11.             Program p = new Program();  
  12.             Console.WriteLine(p.flag);  
  13.             Console.ReadKey();  
  14.         }  
  15.     }  
Explaination :
 
There is two possibility to define value to readonly property :
 
1 . You can directly define when declaration like :
 
  1. readonly bool flag =false ;  
2 . Define value with constructor  :
 
  1. Program()  
  2.         {  
  3.             flag = true;  
  4.         }  
I hope it helps 
 
Thanks
 
Accepted
1
Manav Pandya

Manav Pandya

NA 7.1k 24k 7y
Hello 
 
Always welcomed any doubts in future !!!
 
Thanks 
1
Dinesh Kudale

Dinesh Kudale

NA 7 147 7y
Thank you Manav Pandya !   You have cleared my doubt.