none
Error: Invalid token '=' in class, struct, or interface member declaration RRS feed

  • Question

  • 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()
     {  
     }
    }

    Saturday, January 13, 2018 4:15 AM

Answers

  • Answer:

    • We can assign the value for readonly at the time of declaration
    • or
    • we can also assign the value for readonly through constructor.
     

    I 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.     }  

    Explanation:

     

    There are two possibilities to define value to readonly property:

     

    1. You can directly define when declaration likes:

     

    1. readonly bool flag =false ;  

    2. Define value with constructor:

     

    1. Program()  
    2.         {  
    3.             flag = true;  

            } 

    • Marked as answer by Dinesh Kudale Saturday, January 13, 2018 7:12 AM
    Saturday, January 13, 2018 7:11 AM

All replies

  • You have to assign it when you define it:

    readonly bool flag = true;


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Saturday, January 13, 2018 5:53 AM
    Moderator
  • Answer:

    • We can assign the value for readonly at the time of declaration
    • or
    • we can also assign the value for readonly through constructor.
     

    I 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.     }  

    Explanation:

     

    There are two possibilities to define value to readonly property:

     

    1. You can directly define when declaration likes:

     

    1. readonly bool flag =false ;  

    2. Define value with constructor:

     

    1. Program()  
    2.         {  
    3.             flag = true;  

            } 

    • Marked as answer by Dinesh Kudale Saturday, January 13, 2018 7:12 AM
    Saturday, January 13, 2018 7:11 AM