views:

81

answers:

3
IList<string> strList = new string[] { "Apple", "Mango", "Orange" };

IList<string> lst = new ReadOnlyCollection<string>(new[]{"Google",
"MSN","Yahoo"});

In both cases i can not use "Add()" method for adding new items.then almost both declarations are same?

+3  A: 

With the first, strList[2] = "Pear"; will work... not with the second. Arrays are always mutable in that you can re-assign by index, even if you can't add/remove. A read-only-collection is just that: read-only.

Marc Gravell
+3  A: 

The items in strList can be changed (not added or removed, but changed).

Lucero
+2  A: 

In the first declaration, you can still use the following:

strList[0] = "Not a fruit";

ReadOnlyCollection<T> wraps any IList<T> in a lightweight object. It passes all calls that wouldn't change the collection on to the wrapped object (get Count, get Item[], GetEnumerator), but throws an exception for all calls that would change the collection (Add, Remove, Clear, set Item[]).

Arrays are not resizable, but they are not readonly. The distinction is important to understand or you can introduce some serious security issues, for an example see Path.InvalidPathChars Field.

280Z28