Friday, November 1, 2019

c# - Having a collection in class

Answer


Answer





There are several options when one class must have a container (collection) of some sort of objects and I was wondering what implementation I shall prefer.



Here follow the options I found:




public class AClass : IEnumerable{
private List values = new List()

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

public IEnumerator GetEnumerator(){
return values.GetEnumerator();

}
}


Pros: AClass is not dependent on a concrete implementation of a collection (in this case List).



Cons: AClass doesn't have interface for Adding and removing elements



public class AClass : ICollection{
private List values = new List()


IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

public IEnumerator GetEnumerator(){
return values.GetEnumerator();
}


//other ICollectionMembers
}


Pros: Same as IEnumerable plus it have interface for adding and removing elements



Cons: The ICollection interface define other methods that one rarely uses and it get's boring to implement those just for the sake of the interface. Also IEnumerable LINQ extensions takes care of some of those.



public class AClass : List{


}


Pros: No need of implementing any method. Caller may call any method implemented by List



Cons: AClass is dependent on collection List and if it changes some of the caller code may need to be changed. Also AClass can't inherit any other class.



The question is: Which one shall I prefer to state that my class contains a collection supporting both Add and Remove operations? Or other suggestions...


Answer



My suggestion is just define a generic List inside of your class and write additional Add and Remove methods like this and implement IEnumerable:




public class MyClass : IEnumerable
{
private List myList;

public MyClass()
{
myList = new List();
}


public void Add(string item)
{
if (item != null) myList.Add(item);
}

public void Remove(string item)
{
if (myList.IndexOf(item) > 0) myList.Remove(item);
}


public IEnumerable MyList { get { return myList; } }

public IEnumerator GetEnumerator()
{
return myList.GetEnumerator();
}
}


This is the best way if you don't want to implement your own collection.You don't need to implement an interface to Add and Remove methods.The additional methods like this fits your needs I guess.



No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...