tags:

views:

83

answers:

3

I basically want to do this in code:

PersonList myPersonList;
//populate myPersonList here, not shown

Foreach (Person myPerson in myPersonList)
{
...
}

Class declare

public class PersonList
{
 public List<Person> myIntenalList;

 Person CustomFunction()
 {...}
}

So how do I expose "myInternalList" in my class as the default value that the Foreach statement can use it? Or can I? Reason being is that I have about 50 classes that are currently using GenericCollection that I'd like to move to generics but don't want to re-write a ton.

+4  A: 

The easiest way is to inherit from your generic list:

public class PersonList : List<Person>
{
   public bool CustomMethod()
   { 
     //...
   }

}
C. Ross
This exposes also the methods for altering the list, I don't know whether this is indeded by the OP. If not use Lee's solution.
Obalix
It's generally not a good idea to inherit from the .NET collection classes. See my response here: http://stackoverflow.com/questions/2136213/c-inherit-from-dictionary-iterate-over-keyvaluepairs/2136235#2136235.
LBushkin
@LBushkin That's only necessary if they want to override add, etc. But still something good to keep in mind.
C. Ross
+1  A: 

Why don't you simply change the base class on PersonList to be Collection<Person>? Persumably it can already enumerate on Person, so your foreach would still work.

Thomas
+8  A: 

You could make PersonList implement IEnumerable<Person>

public class PersonList : IEnumerable<Person>
{
    public List<Person> myIntenalList;

    public IEnumerator<Person> GetEnumerator()
    {
         return this.myInternalList.GetEnumerator();
    }

    Person CustomFunction()
    {...}
}

Or even simpler, just make PersonList extend List:

public class PersonList : List<Person>
{
    Person CustomFunction() { ... }
}

The first method has the advantage of not exposing the methods of List<T>, while the second is more convenient if you want that functionality. Also, you should make myInternalList private.

Lee
I would choose the solution of having `PersonList` implement `IEnumerable<Person>` rather than inheriting from `List<Person>`. See my answer here for more on that: http://stackoverflow.com/questions/2136213/c-inherit-from-dictionary-iterate-over-keyvaluepairs/2136235#2136235
LBushkin