Is ReadOnlyCollection <char> immutable?
With the code below, I get warning CA2104 (DoNotDeclareReadOnlyMutableReferenceTypes)
public readonly ReadOnlyCollection<char> IllegalChars; with error message part
change the field to an immutable reference type. If the reference type "ReadOnlyCollection" is, in fact, immutable, exclude this message.
I am sure that ReadOnlyCollection is immutable, but my question is: is there a type that I can use to prevent this message from being displayed?
You can rewrite the public field in the property:
public ReadOnlyCollection<char> IllegalChars { get; private set; } or to exclude a code analysis warning because the collection cannot be changed. The problem is that FxCop cannot detect that ReadOnlyCollection<T> is actually immutable.
I am sure ReadOnlyCollection is immutable.
It is immutable in the sense that you cannot change which collection it wraps, or change this collection through it.
This is not immutable in the sense that since ReadOnlyCollection is a wrapper, it can be mutated by modifying the base collection:
var list = new List<char>{ 'a', 'b', 'c' }; var ro = new ReadOnlyCollection<char>(list); list.Add('d'); Console.WriteLine(string.Join(",", ro)); // a,b,c,d However, you can certainly have a ReadOnlyCollection , which is unchanged in practice without having a link to the base collection anywhere (the easiest way is to copy it when building, or create only this collection when you first build a readonly wrapper, and then it doesn’t have another link).
Doing this will mean that you keep yourself in the spirit of CA2104, in that you are immune to the problems that he was going to save. Then it would be wise to suppress the warning.
I would be more careful about public fields, preferring properties if I wasn’t sure that I needed an area, but that’s another matter.