Down-casting of Typed Collection (Casting Generic Types?)

C

conchur

Is there an elegant way to have a class utilise an inherited method to
return a Typed Collection of itself?

Example:

class MyList<T> : List<T> where T : MyRoot
{
Add...
Remove...
}

abstract class MyRoot
{
public static MyList<MyRoot> List(...)
{
// return MyList<MyRoot>
MyList list = new MyList<MyRoot>();
MyRoot obj = new MyRoot();
list.Add(obj);
return list;
}
}

class MyObj : MyRoot
{
public static MyList<MyObj> List(...)
{
// need to cast MyList<MyRoot> as MyList<MyObj>
return (MyList<MyObj>) base.List(...);
}
}

Obviously this simplified code is seriously flawed - but hopefully you
understand what I'm trying to achieve.

I want a static method of MyObj to return a List of MyObj objects, but
the implementation of this method should ideally be in the abstract
base class. The actual scenario I'm playing with is a Data Access
Layer using a Collection of data objects with a shared base which
handles all the database connectivity. The objects simply expose the
resultant fields as properties and inherit the Save(), Load(), List()
methods.

Is it possible to have an arbitrary number of static methods (some
static) which return a Collection of the expected type by calling the
relevant base class method? I'm trying to encapsulate as much of the
code as possible in th base class to make the derived classes as simple
as possible.

// static method on derived class
ObjectList<Person> ukPeople = Person.ListByCountry("UK");

// instance method on derived class
Person bob = new Person("bob");
ObjectList<Person> bobsPeople = bob.ListStaff();


Any ideas or pointers?

Thanks,
Conchur.
 
C

conchur

This has been neatly answered in another thread a day later ("Question
about Generics" by hammad_awan mirrored at
http://groups.google.com/group/micr....csharp/browse_thread/thread/b47879b2fecdf61a
)
so I thought I should close this one by pointing interested parties
over there instead.

In summary, this sort of casting is known as 'covariance' and is not
supported by the C# language at present (although it is apparently
supported at compiler level).

Barry Kelly posted a link to an interesting article on a proposed C#
extension to add this functionality:
http://research.microsoft.com/research/pubs/view.aspx?type=inproceedings&id=1215

Thanks!
 

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