Question

public class Kuku
{
    private LinkedList<MyClass> m_list;
    public IEnumerable<MyClass> Locations { get { return m_list; } }
}

I need to implement in public class FindAllMyClass the method which iterates all MyClass objects in Kuku - I don't know how do I use Locations property from Kuku.

Should I define IEnumerable Locations or just make LinkedList m_list to be public property?

Should I define IEnumerable<MyClass> Locations or just make LinkedList<MyClass> m_list to be a public property?

public class FindAllMyClass
{
    public void itMethod(Kuku input)
    {
        //This is not correct
        foreach (MyClass c in input.Locations)
        {
        }
    }
}
Was it helpful?

Solution

Why to define IEnumerable Locations and not just make LinkedList m_list to be public property?

Several possible reasons:

  • What if later you decide you don't want to implement it as a LinkedList<> but as a regular List? Or a lazy-loaded collection type? or an array?

  • Exposing the collection as a generic IEnumerable<T> allows you to change out the internal implementation later without changing the public contract.

  • If you make the collection a property (with get; set; accessors) you are allowing clients to add to, remove from, even replace the entire list. Exposing it as IEnumerable indicates that the list is intended to be read-only (unless you expose Add methods somewhere else).

I don't know how do I use Locations property from Kuku.

Sure you do - you're already doing it in your sample:

foreach (MyClass c in input.Locations)
{
}

Or you can use Linq to search for or aggregate data from the collection (foreach is still appropriate for updating the instances.

OTHER TIPS

You could use LINQ to object:

input.Locations.Where(x=> x.Property1 == value1 && x.Property2 > value2);

IEnumerable gives you a way to expose a list from your class which has the following properties:

  • It is implementation independent - you can change what sort of list you use internally without needing to change everything which uses your class
  • It integrates well with LINQ, foreach and various other language constructs
  • It provides a read only view on the list, so no chance of others updating the list (inserting/deleting items)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top