locked
PROPERTY VS DIRECT ACCESS

    Question

  • Consider the following little example:

    class C
    {
        private List<T> _list;
        public List<T> list { get { return _list; } }

        ...
    }

    One tries to hide the internal implementation of _list, however the property 'list' is a reference to the internal _list and enables whatever operation, including e.g. list.Clear().

    It seems to me there is no difference if the list was declared public:

    class C
    {
        public List<T> list;

        ...
    }

    I would like instead to prevent the external user make any change to the internal _list: the property should give just a read-only access.

    Is it possible (in a simple way)?

    Friday, May 16, 2014 3:45 PM

Answers

  • Yes. That will generate the read only wrapper I hinted at. Good catch.

    --Rob

    • Marked as answer by GiorgioITA Saturday, May 17, 2014 9:56 AM
    Friday, May 16, 2014 7:15 PM
    Owner

All replies

  • You can return a copy of the list rather than the main one. That way the consuemer's edits won't affect the master list.

    Another option would be to return a wrapper which implements IList<T> and passes the reading methods through but blocks the editing methods.

    --Rob

    Friday, May 16, 2014 5:08 PM
    Owner
  • I'm not an expert on this -- but would .AsReadOnly work for you?

    http://msdn.microsoft.com/en-us/library/e78dcd75(v=vs.110).aspx

    Friday, May 16, 2014 6:04 PM
  • Yes. That will generate the read only wrapper I hinted at. Good catch.

    --Rob

    • Marked as answer by GiorgioITA Saturday, May 17, 2014 9:56 AM
    Friday, May 16, 2014 7:15 PM
    Owner
  • Thank you for the good hints.
    Saturday, May 17, 2014 9:56 AM