I have a parent class which is essentially a glorified list. It's extended by several subclasses for various functionalities.
public class HierarchialItemList<ItemType> : IEnumerable<ItemType>
{
public ItemType this[String itemCode]
{
get
{
foreach (IHierarchialItem curItem in hierarchialItems)
{
if (curItem.Code.Equals(itemCode, StringComparison.CurrentCultureIgnoreCase))
{
return ((ItemType)curItem);
}
}
return (default(ItemType));
}
}
public ItemType this[Int32 index]
{
get
{
return (hierarchialItems[index]);
}
}
}
public class DatabaseList : HierarchialItemList<Database>
{
public DatabaseList this[CommonDatabaseType typeToFilter]
{
get
{
DatabaseList returnList = new DatabaseList();
foreach(Database curDatabase in this)
{
if (curDatabase.DatabaseType.Equals(typeToFilter))
{
returnList.Add(curDatabase);
}
}
return (returnList);
}
}
public DatabaseList this[Environments.RMSEnvironment environmentToFilter]
{
get
{
DatabaseList returnList = new DatabaseList();
foreach(Database curDatabase in this)
{
if (curDatabase.ParentEnvironment.Equals(environmentToFilter))
{
returnList.Add(curDatabase);
}
}
return (returnList);
}
}
}
The problem is that C# thinks that this:
Database testDatabase = sampleDatabaseList[0];
Is an error and that the indexer should be returning a DatabaseList, not a Database. You and I both know that's false. Any workarounds or do all indexers have to have the same return type?
Edit: I just figured out that it's because of using an enumeration as an indexer which is internally an integer. Still, any way to use both an enumeration and an integer?
Edit 2: As requested, here is some compiliable test code which demonstrates the problem.
using System;
using System.Collections.Generic;
namespace CSQT
{
class A<T>
{
List<T> temp;
public A()
{
temp = new List<T>();
}
public void AddItem(T itemToAdd)
{
temp.Add(itemToAdd);
}
public T this[String code]
{
get { return (temp[0]); }
}
public T this[Int32 index]
{
get { return (temp[index]); }
}
}
class B : A<String>
{
public B()
: base()
{
}
public B this[BTypes testType]
{
get
{
return (this);
}
}
}
enum BTypes { TEMP1, TEMP2 };
class C
{
public C()
{
B temp = new B();
//Compile error: Cannot implicitly convert type 'CSQT.B' to 'string'
String temp2 = temp[0];
//Compile error: Cannot convert type 'CSQT.B' to 'string'
String temp3 = (String)temp[0];
//This compiles and runs but instead of going to A.this[int32], it goes to B.this[BTypes testType]
B temp4 = temp[0];
}
}
}