interface IFolderOrItem<TFolderOrItem> where TFolderOrItem : FolderOrItem {}
abstract class FolderOrItem {}
class Folder : FolderOrItem {}
abstract class Item : FolderOrItem {}
class Document : Item {}
now i’m trying to do sth like this:
class Something
{
IFolderItemOrItem<Item> SelectedItem { get; set; }
void SomeMagicMethod()
{
this.SelectedItem = (IFolderOrItem<Item>)GetMagicDocument();
// bad bad bad ... ??
}
IFolderOrItem<Document> GetMagicDocument()
{
return someMagicDocument; // which is of type IFolderOrItem<Document>
}
}
is there any possibility to get this working?
If I read it correctly… then the problem is that just because
Foo : Bar, that does not mean thatISomething<Foo> : ISomething<Bar>…In some cases, variance in C# 4.0 may be an option. Alternatively, there are sometimes things you can do with generic methods (not sure it will help here, though).
The closest you can do in C# 3.0 (and below) is probably a non-generic base interface:
commonly, the base-interface would have, for example, a
Type ItemType {get;}to indicate the real type under consideration. Then usage:From the spec, this relates to §25.5.6 (ECMA 334 v4):
The same applies to interfaces. This changes a bit in C# 4.0, but only in some cases.