Click here to Skip to main content
15,896,489 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
what would happen by using the readonly modifier on the list container.

For example:

C#
class Test
{
  private readonly list<string> stringTest = new List<string>();

test()
{}

void changeStringTest()
{
  stringTest.Add("hello");
//Why i am allowed to do this. Readonly should prevent me from doing this by definition where i should only modify the list in the constructor or during initialization 
}

}


Also what is then the difference of readonlycollection<string>


Thanks in Advance
Posted
Comments
SoumenBanerjee 7-Nov-12 1:17am    
View this link
http://msdn.microsoft.com/en-us/library/ms132474.aspx

1 solution

When you apply "readonly" keyword to a reference, you prevent the reference from changing the object it is pointing to but it is legal to change the object itself.
In your case, when stringTest is first initialzed, you are not allowed to create a new List<string> object and assign it to stringTest later in your application.

C#
class Test
{
  private readonly list<string> stringTest = new List<string>();

  test(){}
 
  void changeStringTest()
  {
     /* NOT ALLOWED. stringTest is readonly. Its not allowed to change
        the object it is pointing to. */
     stringTest = new List<strnig>();
     
     /* ALLOWED. You are not going to change stringTest but the object.
        Because adding a new item to a list does not affect the
        reference (stringTest) but the object whitch is pointed to by
        stringTest. */
     stringTest.Add("hello");
  }
}
</strnig></string></string>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900