Keyed Collection and derived classes

S

SP

I have created an abstract class inheriting from KeyedCollection<long,
TItem> to use as a base class for my collections. In some derived classes I
am providing a new indexer property for the key (long). I need to access my
collection by index and by key however the new long indexer is used for BOTH
int and long, i.e. myCollection[(int)0] will use the long indexer NOT the
base classes int indexer. Why is that? The workaround is to also define a
new int indexer in the derived class but this should not be necessary.

SP
 
S

SP

Sample code to demonstrate the problem.

static void Main(string[] args)
{
MyItemCollection collection = new MyItemCollection();
collection.Add(new MyItem(50));
collection.Add(new MyItem(60));

// this should use the public int indexer defined in MyBaseCollection<TKey,
TItem>
Console.WriteLine(collection[(int)0].MyLongKey == 50);
}



public class MyBaseCollection<TKey, TItem> : KeyedCollection<TKey, TItem>
{
protected override TKey GetKeyForItem(TItem item)
{
return default(TKey);
}

public new TItem this[int index]
{
get
{
return base.Items[index];
}
}
}

public class MyBaseCollection<TItem> : MyBaseCollection<long, TItem>
where TItem : ILongKeyed
{
protected override long GetKeyForItem(TItem item)
{
return item.MyLongKey;
}
}

public interface ILongKeyed
{
long MyLongKey
{
get;
}
}

public class MyItemCollection : MyBaseCollection<MyItem>
{
public new MyItem this[long key]
{
get
{
return base[key];
}
}
}

public class MyItem : ILongKeyed
{
public MyItem(long key)
{
this.key = key;
}

private long key;
public long MyLongKey
{
get
{
return this.key;
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top