Proper use of properties when working with a collection

I am wondering how to make the best use of properties when working with collections.

For example, I have a class Foo, and I want to have a list of this class. Which of the following should be used:

private List<Foo> myList;
private List<Foo> myOtherList = new List<Foo>();

now for the property:

public List<Foo> ListOfFoo
  {
     get 
     { 
        return myList; 
     }
     set 
     { 
        myList= new List<Foo>(value); 
     }
  }

Or should the set be just a value?

public List<Foo> ListOfFoo
  {
     get 
     { 
        return myList; 
     }
     set 
     { 
        myList= value; 
     }
  }
+3
source share
5 answers

Select

private List<Foo> myOtherList = new List<Foo>();

becuse the other simply declares a link (which is set to null), the sample above declares a link to a list, creates a list and assigns this new list to a link.

Select

public List<Foo> ListOfFoo
  {
     get { return myList; }
     set { myList= new List<Foo>(value); }
  }

If you want myList to not return any changes that happen to the list after it is assigned to myList, for example.

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

List<string> mySecondList = new List<string>(myFirstList); 
// mySecondList now contains Hello & world

myFirstList.Add("Boyo");
// myFrist List now contains Hello, world & Boyo
// mySecondList still contains Hello & world

Select

public List<Foo> ListOfFoo
  {
     get { return myList; }
     set { myList= value; }
  }

, , .

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

List<string> mySecondList = myFirstList; 
// mySecondList now contains Hello & world

myFirstList.Add("Boyo");
// myFrist List now contains Hello, world & Boyo
// mySecondList "also" contains Hello, world & Boyo 

"" , , .

+2

, List<T> ( Collection<T>), , , - , Clear, Add .., .

:

class Foo
{
    Collection<Bar> _bars = new Collection<Bar>();

    public Collection<Bar> Bars { get { return _bars; } }
}

Collection<T> InsertItem, SetItem ..

+2

.

, , ..Net . .

, , - , .

0

, (ICollection, IList ) :

private IList<Foo> m_list = new List<Foo>();
public IList<Foo> List {get { return m_list; } }

: , . . , m_list , , . .

. , :

  • (, ).
0

IEnumerator-Interface , , .

This way you also hide the actual implementation of the list.

class FooBar : IEnumerator
{
  private Collection<Foo> col;

  public IEnumarator GetEnumerator()
  {
    return col.GetEnumerator();
  }

  public void SetList(Collection col)
  {
    this.col= col; // you can also make this more general and convert the parameter so it fits your listimpl.
  }
}

class Clazz
{
  private void WhatEver(){
    FooBar foobar = new FooBar();
    ...
    foreach(Foo f in foobar)
    {...}
  }
}
0
source

Source: https://habr.com/ru/post/1708737/


All Articles