Skip to main content
GameDev.net gamedev.net
🔒 Locked

Readonly members of an array or list.

Started by Thevenin Jul 14, 2008 at 5:51 PM 3 replies 1.6k views
Original Post
Thevenin
Thevenin
I have a book, which is basically either an array of pages, or a List<> of pages. The pages are intended to be READONLY; I don't want it to be possible to compile MyBook[2] = null;
public abstract cPages[] MyBook
{
get;
}
Essentially, what I want to be able to do exactly is:
public abstract List<readonly cPages> MyBook
{
get;
}
How should I code this?
Trillian
Trillian
If you want the array to be read-only, use a read-only collection wrapper such as System.Collection.ObjectModel.ReadOnlyCollection (you might be better rolling up your own to support generics). More easily, make your property return a IEnumerable

If you want the items of the array to be read-only, then its a bit more complex. Your List makes me think you come from a C++ background. There's no such feature in C#, you'll have to do a wrapper for your cPages class that only has getters, and then maybe a wrapper over your collection that will enable to iterate over your readonly item wrappers instead of the items themselves.

Its a bit of work, but there's no easier way, AFAIK.
Thevenin
Thevenin
Interfacing IEnumerable<> seems like more work than I'm willing to commit to this very small section of a much larger project.

I know that it is impossible to do what I want to do (at least in C#), but I'm hoping for a more convenient workaround than defining a subclass that has a "this[int index]" on it.

Personally, I perfer the subclass than interfacing IEnumerable.

        public class cBook        {            string[] MyPages;            public cBook(string[] ThePages)            {                MyPages= ThePages;            }            public cBook this[int TheIndex]            {                get                {                    return MyPages[TheIndex];                }            }            public int MyCount            {                get                {                    return MyPages.Length;                }            }        }


However, "ReadOnlyCollection" looks EXACTLY like what I want.

Thanks! [grin]
ratings++;

P.S.: I think since .NET Framework 2.0, there has been a generic implementation of ReadOnlyCollection.
Nitage
Nitage
It may or may not be what you want.

The elements in a ReadOnlyCollection can still be altered by calling mutating member functions or set properties. If you want the equivilent of a C++ const type, you'll need a new class that provides no mutating member functions or set properties.
hh10k
hh10k
You could use List.AsReadOnly(), which will return a ReadOnlyCollection for you.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.