Note that there are some explanatory texts on larger screens.

plurals
  1. POC# .Net 3.5 Using Overloaded Indexers with different return types
    text
    copied!<p>I have a parent class which is essentially a glorified list. It's extended by several subclasses for various functionalities.</p> <pre><code>public class HierarchialItemList&lt;ItemType&gt; : IEnumerable&lt;ItemType&gt; { 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&lt;Database&gt; { 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); } } } </code></pre> <p>The problem is that C# thinks that this:</p> <p><code>Database testDatabase = sampleDatabaseList[0];</code></p> <p>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?</p> <p>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?</p> <p>Edit 2: As requested, here is some compiliable test code which demonstrates the problem.</p> <pre><code>using System; using System.Collections.Generic; namespace CSQT { class A&lt;T&gt; { List&lt;T&gt; temp; public A() { temp = new List&lt;T&gt;(); } 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&lt;String&gt; { 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]; } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload