tags:

views:

62

answers:

4

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]);
        }

    }
}
+6  A: 
public MailAddress this[int index] 
{
   get { return ((MailAddress)(base.Items[index]); }
}
Anna Lear
Only problem... the base class already defines this indexer.
Brian Genisio
@Brian: it can be hidden with the 'new' keyword.
Anna Lear
I needed the new keyword. "public new MailAddress this[int index]"
SchwartzE
+3  A: 

See this question: How do I overload the square-bracket operator in C#?

pst
+2  A: 

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
A: 

Or alternatively

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