views:

227

answers:

5

I ran a security code analyst i found myself having a CA2105 warning. I looked at the grade tampering example. I didn't realize you can assign int[] to a readonly int. I thought readonly was like the C++ const and makes it illegal.

The How to Fix Violations suggest i clone the object (which i don't want to do) or 'Replace the array with a strongly typed collection that cannot be changed'. I clicked the link and see 'ArrayList' and adding each element one by one and it doesn't look like you can prevent something adding more.

So when i have this piece of code what is the easiest or best way to make it a read only collection?

public static readonly string[] example = { "a", "b", "sfsdg", "sdgfhf", "erfdgf", "last one"};
+3  A: 
var readOnly = new ReadOnlyCollection<string>(example);
Mark Seemann
+5  A: 
public static readonly ReadOnlyCollection<string> example
    = new ReadOnlyCollection<string>(new string[] { "your", "options", "here" });

(although it should still probably be exposed as a get property rather than a public field)

Marc Gravell
+1  A: 
ReadOnlyCollection<string> readOnlyCollection = 
            new ReadOnlyCollection<string>(example);
Kyle Rozendo
+8  A: 

The easiest way to have a collection which you cannot modify is to use

ReadOnlyCollection

Example from MSDN:

List<string> dinosaurs = new List<string>();
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");

ReadOnlyCollection<string> readOnlyDinosaurs = new ReadOnlyCollection<string>(dinosaurs);
Mikael Svenson
+1  A: 

If you're working with arrays, you can use

return Array.AsReadOnly(example);

to wrap your array in a read-only collection.

Steve Dennis