Overloading Index Operator
-
Is it possible in C#? I have a class, Hand. It contains an Array of cards. I have defined a property in the array which returns the array of cards that it contains, but it makes for convoluted syntax: Player.Cards.Card[1]; Where Player.Cards refers to the "hand" a player holds. If my Hand class looks something like: public class Hand private Card[] m_Hand; public Hand(params Card[] cards) { m_Hand = cards; } public Card[] Cards { get { return m_Hand; } } } Can I simply overload the index operator for my Hand class and get rid of the Cards property? So I could do something like: Player.Cards[0]; Would refer to: Player.Cards.m_Hand[0]; That make sense? As always, thanks!
-
Is it possible in C#? I have a class, Hand. It contains an Array of cards. I have defined a property in the array which returns the array of cards that it contains, but it makes for convoluted syntax: Player.Cards.Card[1]; Where Player.Cards refers to the "hand" a player holds. If my Hand class looks something like: public class Hand private Card[] m_Hand; public Hand(params Card[] cards) { m_Hand = cards; } public Card[] Cards { get { return m_Hand; } } } Can I simply overload the index operator for my Hand class and get rid of the Cards property? So I could do something like: Player.Cards[0]; Would refer to: Player.Cards.m_Hand[0]; That make sense? As always, thanks!
Yes you can, using
this
as a property name and optionally using theIndexerNameAttribute
to get it a name (for some languages like VB.NET have to refer to the indexer while C# doesn't) other than "Item":public class Hand
{
// ...
[System.Runtime.CompilerServices.IndexerName("Card")] // Optional
public Card this[int index]
{
get { return m_Hand[index]; }
}
// ...
}This posting is provided "AS IS" with no warranties, and confers no rights. Software Design Engineer Developer Division Customer Product-lifecycle Experience Microsoft [My Articles] [My Blog]