Allowing access to an internal ArrayList through IEnumerator?

M

Matthias S.

Hi,

I'm trying to provide the user of my class access to the objects in a
collection without allowing him to modify (add/remove/clear items) the
collection. I thought I can do it by providing a IEnumerator. But this
thingy can't be used directly, as shown in the code below. How can this
be done?

Thanks in advance.

Matthias

Here the test I tried:

using System;
using System.Collections;
using System.Collections;

public class MyClass
{
public static void Main()
{
string s1 = "Hello";
string s2 = "World!";
a.Add(s1);
a.Add(s2);

foreach (String s in GetEnumerator())
Console.WriteLine(s);
}

private static IEnumerator GetEnumerator() {
return a.GetEnumerator();
}
private static ArrayList a = new ArrayList();
}
 
N

Nicholas Paldino [.NET/C# MVP]

Matthias,

An enumerator is used for enumerating through the items in a list, not
for providing read-only access. If you want to provide read-only access to
an ArrayList, then call the static ReadOnly method on the ArrayList class,
which will return an ArrayList which is read-only (it will throw an
exception if you try and modify the list in any way).

Be careful though, if you have object references in your array list,
then your objects could be modified, they are not read only, just the list.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top