Connecting Tech Pros Worldwide Help | Site Map

Casting List<> of classes to interfaces

Newbie
 
Join Date: Mar 2007
Posts: 1
#1: Mar 2 '07
Hi All,

I'm having problems implementing a readonly interface to a set of classes.
Heres a simplification of the code:

interface IreadonlyBase
{ // Does gets only on base class
}

class baseclass : IreadonlyBase
{ // Does gets and sets as usual
}

interface IreadonlyDerived : Ireadonlybase
{ // Does gets only on derived class & base class
}

class derivedclass : baseclass, IreadonlyDervied
{ // Does gets and sets as usual
}

class container
{
private List<baseclass> baseclassitems;
public ReadOnlyCollection<Ireadonlybase> ReadOnlyBases
{
// Should return a readonly version of the baseclassitems that can be traversed
get{return new ReadOnlyCollection<IReadOnlyEntity>(baseclassitems )};
}
}

Problem is the compiler refuses to accept the baseclassitems as a list of Ireadonly even though each base class derives from Ireadonly, why can i not cast a List<baseclass> to List<Ireadonlybase> if every base is a Ireadonly base?
I don't want to have to recreate the baselist again (in terms of interfaces) just to access it in a readonly manner.
Is this a logical approach to the readonly problem or am i overlooking something completely more obvious!

Many thanks for any help you can give.
Reply