simple generics IList question

P

Peter Kirk

Hi

I have never used generics before, and I was wondering if the following sort
of use was acceptable/normal for a method:

public IList<IPerson> GetPersons()
{
IList<IPerson> personList = new List<IPerson>();
... // get the persons
return personList;
}


The meaning is that I return a "List" which holds only "IPerson" objects. In
earlier projects I have made without generics, I would have returned a
normal IList (eg ArrayList) or an array IPerson[].


Then I think the client should call it like:

IList<IPerson> persons = GetPersons();


Thanks,
Peter
 
J

Jon Skeet [C# MVP]

Peter said:
I have never used generics before, and I was wondering if the following sort
of use was acceptable/normal for a method:

public IList<IPerson> GetPersons()
{
IList<IPerson> personList = new List<IPerson>();
... // get the persons
return personList;
}

The meaning is that I return a "List" which holds only "IPerson" objects. In
earlier projects I have made without generics, I would have returned a
normal IList (eg ArrayList) or an array IPerson[].

Then I think the client should call it like:

IList<IPerson> persons = GetPersons();

Yes, that's absolutely fine, and a very normal way of using generics.

Warning: relatively complex stuff follows. If you're happy with just
the above, feel free to skip the stuff below. If you want to know more
about generics for the sake of interest, however, this may be useful.

One thing you *may* be surprised about is that you can't do:

IList<IPerson> list = new List<Person>();

where Person implements IPerson. C# generics doesn't have the concept
of covariance/contravariance (yet). (With covariance/contravariance
you'd need to have slightly different syntax to the above in order to
say it was a "list of some unspecified type which implements IPerson".
That would have to prevent you from adding new objects (as they might
not be of the right type) but would still allow objects to be fetched
as IPerson.)

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top