Property List

When implementing setter for the List property (in C #), this is bad, what to write:

    private List<string> _TheList = new List<string>();
    public List<string> TheList
    {
        get { return _TheList; }
        set { _TheList = value; }
    }

If it will not be written as:

    private List<string> _TheList = new List<string>();
    public List<string> TheList
    {
        get { return _TheList; }
        set { _TheList = new List<string>(value); }
    }

Until today, I usually used the former, but recently found code that used the latter, and it seemed like this was probably the right way to implement this.

The old reason will not be used for the TheList property to be changed when changes are made to the external list that is assigned to it. For instance:

List<string> list = new List<string>();
list.Add("Hello");

var c = new someClass();
c.TheList = list;

Using the first will not cause the following code to break TheList encapsulation:

list.Clear();

Now c.TheList is also empty, which may not be the way we wanted. However, using the latter approach, c.TheList will not be cleared.

+5
source share
6 answers

.

Collection<T>, List<T>.

: :

(, var list = Thingy.TheList), , . ( , )
, , .

Collection<T> List<T> . ( Collection<T> InsertItem ). ​​ .

+7

, , , , , . :

   private List<string> _TheList = new List<string>();
public List<string> TheList
{
    get { return _TheList; }
}

, , _TheList

+6

, , . , . , . , .

, , , , .

+3

-, . IList, List (fxcop List ).

-, , . , ///etc. , .

0

, . , , , .

, SLaks , ,

0

, . :

c.TheList = list.ToArray().ToList(); 
0

All Articles