Groups | Blog | Home
all groups > c# > october 2005 >

c# : how to over ride operator []?


Daniel O'Connell [C# MVP]
10/21/2005 9:44:39 PM

[quoted text, click to view]

You have to define an indexer:

public <type> this[<parameter list>]
{
get { }
set { }
}
[quoted text, click to view]

Richard Lewis Haggard
10/21/2005 10:36:29 PM
What is the syntax to over ride the array index operator '[]'?

I want to derive a class from CollectionBase and have it encapsulate an
array of another class I'm working with. Among other things, it needs to
over ride the [] operator but I don't seem to be able to get the syntax
quite right. Can someone tell me what the syntax should be in order to over
ride the operator[]?
--
Richard Lewis Haggard

ALI RAZA
10/22/2005 12:00:00 AM
Salam

In addition to Richard Lewis Haggard solution, you must also use a OVERRIDE
keyword, in order to override this function.

--
ALI RAZA SHAIKH
MCAD.net

www.programmersparadise.cjb.net
alirazashaikh.blogspot.com

"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in
message news:OQHSiKr1FHA.3780@TK2MSFTNGP12.phx.gbl...
[quoted text, click to view]

Daniel O'Connell [C# MVP]
10/22/2005 2:30:33 PM

[quoted text, click to view]

Note that this is only applicable when the indexer is overriding a virtual
indexer on the parent class. It isn't required for new indexers.

Richard Lewis Haggard
10/22/2005 6:03:29 PM
Thanks, but I couldn't quite seem to implement your suggestion. Here's what
I want to do - make a class that's derived from ArrayList and contains an
array of CAccount objects. I tried this:

class CAccounts : ArrayList
{
public override CAccount this[ int iIndex]
{
get { List[iIndex]; }
set { List[iIndex]; }
}
}
But that resulted in the following error:

'HAPTimeClock.CAccounts.this[int]: type must be 'object' to match overriden
member 'System.Collections.ArrayList.this[int]

I tried several more variations but nothing seemed to make the C# compiler
happy.

--
Richard Lewis Haggard

"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in
message news:OQHSiKr1FHA.3780@TK2MSFTNGP12.phx.gbl...
[quoted text, click to view]

Daniel O'Connell [C# MVP]
10/22/2005 6:12:08 PM

[quoted text, click to view]

Thats because you cannot overload based on return type. Don't use ArrayList,
try using CollectionBase instead.
[quoted text, click to view]

AddThis Social Bookmark Button