Overload Indexer

D

Dieter Pelz

Hallo,

could anyone explain why the double indexer ist called and not the
overloaded int indexer.
The Test Object is called with an int Value!

Output:
CALL Test this[double dbl] ??????????????
CALL Test this[int idx]

using System;
public class Test : TestBase
{
public override object this [int idx]
{
get {
Console.WriteLine("CALL Test this[int idx]");
return "Test[int]";
}
}
public object this[double dbl]
{
get {
Console.WriteLine("CALL Test this[double dbl]");
return "Test[double]";
}
}
public static void Main()
{
object obj;
Test tst = new Test();

int i = 2;
obj = tst;
obj = ((TestBase)tst);

Console.ReadLine();

// Output
// CALL Test this[double dbl] ??????????????
// CALL Test this[int idx]
}

};

public class TestBase
{
public virtual object this[int idx]
{
get {
Console.WriteLine("CALL TestBase this[int idx]");
return "TestBase[int]";
}
}
};

Thanks
Dieter
 
S

Steven Cheng[MSFT]

Hi Dieter,

Thanks for your posting. As for the Indexer problem you mentioned, I think
it is the normal behavior of the C# compiler on dealing with indexers. In
fact, when the compiler encounter a certain indexer expression, for example:

class a;

a[index] =

then, the compiler will first create a set of all of the class a's
avaliable indexers and them filter some and finally choose a most
appropriate one. And one rule of the filtering is the indexer which is
defined with
"override" keyword will be bypassed, that's why your override indexer(int
parameter) will not work.

For detailed explanition, you can have a look at the following
specification:

7.5.6.2 Indexer access
http://msdn.microsoft.com/library/en-us/csspec/html/vclrfcsharpspec_7_5_6_2.
asp?frame=true


Thanks.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
 

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