3

I am adding functionality to an existing .Net collection. In order to do this, I am overriding several functions. I have not been able to override the return value of the basic array return in the collection. For example, if I call emailMessage.To[i], it does not return the proper value, but if I call emailMessage.Item(i), it returns the correct value. Below is the code from my class. What do I need to override to correct the first error?

namespace EmailService
{
    public class MailAddressCollection : System.Net.Mail.MailAddressCollection
    {
        public MailAddressCollection() : base()
        {
        }

        public void Add(MailAddress Address)
        {
             base.Add(Address);
        }

        public MailAddress Item(int index)
        {
            return (MailAddress)(base.Items[index]);
        }

    }
}
SchwartzE
  • 2,558
  • 5
  • 30
  • 39
  • 1
    possible duplicate of [How do I overload the square-bracket operator in C#?](http://stackoverflow.com/questions/287928/how-do-i-overload-the-square-bracket-operator-in-c) –  Jul 21 '10 at 19:02
  • See this question: [How do I overload the square-bracket operator in C#?](http://stackoverflow.com/questions/287928/how-do-i-overload-the-square-bracket-operator-in-c) –  Jul 21 '10 at 19:02
  • I think it's better to use composition instead of inheritance in this case to adhere to the [Liskov substitution principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle) – Maksymilian Majer Oct 07 '14 at 11:48

3 Answers3

8
public MailAddress this[int index] 
{
   get { return ((MailAddress)(base.Items[index]); }
}
Adam Lear
  • 38,111
  • 12
  • 81
  • 101
8

You are a little bit out of luck, because MailAddressCollection doesn't set the indexer as virtual.

You CAN use the new keyword:

public new MailAddress this[int index]
{
    get
    {
        return base[index];    
    }           
}

But, your indexer will only work if you have a reference to YOUR collection type. If you use polymorphism, your indexer will not get called.

Brian Genisio
  • 47,787
  • 16
  • 124
  • 167
0

Or alternatively

    public MailAddress this[int index]
    {
        get { return base[index] as MailAddress; }
    }
John Alexiou
  • 28,472
  • 11
  • 77
  • 133