Generic collection interface rules
I am having some problems understanding how to use interfaces within the generic collection framework. I expected the code below to work. publicinterface Reader publicinterface ReadWriter : Reader publicclass MyReadWriter : ReadWriter publicstring GetValue() {return value; } public IDictionary<string, Reader> GetReaders() private IDictionary<string, ReadWriter> GetReadWriters() publicvoid UpdateFred(string value){ [Test] But is generates a compile error in GetReaders(). I then tried to add a cast as follows This compiled but when I ran the code I got a run time error as the same point Test.Tester.TestGenericCollectionBehaviour : System.InvalidCastException : Unable to cast object of type 'System.Collections.Generic.Dictionary`2' to type 'System.Collections.Generic.IDictionary`2'. It seems to me that this should be possible (certainly no unsafe casts needed) but does not seem to work like this. I have have not managed to find any details of the rules surounding the contents of generic collections - any recommendations?
{
string GetValue();
}
{
void SetValue(string value);
}
{
privatestring value;
publicvoid SetValue(string value) {this.value = value; }
}
[TestFixture]
publicclass Tester
{
private IDictionary<string, ReadWriter> readWriters =new Dictionary<string, ReadWriter>();
{
return readWriters;
}
{
return readWriters;
}
IDictionary<string, ReadWriter> collection = GetReadWriters();
if(collection.ContainsKey("Fred")){
collection["Fred"].SetValue(value);
}
}
publicvoid TestGenericCollectionBehaviour()
{
IDictionary<string, ReadWriter> readWriters = GetReadWriters();
IDictionary<string, Reader> readers = GetReaders();
}
}
error CS0266: Cannot implicitly convert type 'System.Collections.Generic.IDictionary<string,Test.ReadWriter>' to 'System.Collections.Generic.IDictionary<string,Test.Reader>'. An explicit conversion exists (are you missing a cast?)
public IDictionary<string, Reader> GetReaders()
{
return(IDictionary<string, Reader>)readWriters;
}

