Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make List items readonly [duplicate]

Possible Duplicate:
List<T> readonly with a private set

I have a class as:

public SomeClass{

        public List<Status> log { get; private set; }

        public enum Status
        {
            waitingForConnection,
            connected,
            receivingFile,
            doneReceivingFile
        }

        // later I initialize log and populate it...
       ///

}

so far it is easy to tell that I am just able to set a new log list from withing the class. How can I prevent users from editing items on the list. In other words I don't want users to be able to do something as:

SomeClass someClass = new SomeClass();
//....
someClass.log[3] = \\different value

if I make the list log private then I will achieve this but I want to enable users to see the content of the log list but not to be able to edit items.

also I don't want to make the public enum Status private so that the user can see the status...

so how can I restrict users from editing the items from the list?

like image 545
Tono Nam Avatar asked Nov 25 '25 09:11

Tono Nam


1 Answers

Use ReadOnlyCollection for this. Also on another note, remember that the readonly keyword does not truly make collections read only.

private List<Status> m_Log = new List<Status>();

public ReadOnlyCollection<Status> Log {
    get {
        return m_Log.AsReadOnly();
    }
}
like image 138
David Anderson Avatar answered Nov 27 '25 00:11

David Anderson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!