Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a class with a generic list and expose that as the default value

Tags:

c#

generics

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.

like image 492
Dilbert789 Avatar asked Dec 07 '22 04:12

Dilbert789


2 Answers

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.

like image 138
Lee Avatar answered Jan 21 '23 00:01

Lee


The easiest way is to inherit from your generic list:

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

}
like image 20
C. Ross Avatar answered Jan 21 '23 00:01

C. Ross