What is true about readonly variable in C# code?

Skill/Topic: Beginner
A) It's the same as a constant
B) It's value can be assigned only once
C) You can never assign a value to it

Showing Answers 1 - 3 of 3 Answers

AmitMishra

  • Nov 29th, 2005
 

B is the right choice. since readonly field can only be initialized at the time of construction of the object. that means if you wanna initialize the readonly property that intialize it inside the constructor.

  Was this answer useful?  Yes

JimmyJamJo

  • May 17th, 2008
 

I'd argue "B" isn't quite right - you CAN assign to a readonly variable more than once, it's just that you can't assign to it after the constructor has been executed. Consider the following (albeit rather contrived) code; the readonly member is assigned to a maximum of three times - once in its initializer, and (potentially) twice during the call to the constructor.

internal class MyClass
{
    private readonly myReadonlyMember = 1;

    public MyClass(int someValue)
    {
       if(someValue > 100)
       {
          myReadonlyMember = (someValue * 2);
          if(someValue == MyOtherClass.SomeConstant)
          {
             myReadonlyMember++;
          }
       }
    }
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions