locked
Turn base class public method into private RRS feed

  • Question

  • Hi there, this is my first post in this forum. Here goes the question...

    I want to create a custom array collection (MyCollection class) , to store objects of a custom class (MyObject class). Something like this:

    public class MyCollection : System.Collections.ArrayList
    {
    }


    Now, i want that only objects of the MyObject class can be added to the collection. So, i tryed to override the Add method, like this:

    public class MyCollection : System.Collections.ArrayList
    {
        /* prevents external calling of this method */
        private override int Add (object o)
        {
            return base.Add(o);
        }

        /* allows add only MyObject objects */
        public int Add (MyObject o)
        {
            return base.Add(o);
        }
    }


    I received the following error:
    Virtul or abstract methods cannot be private.

    So, i tried to use "protected" instead of "private", and i still have error:
    cannot change access modifiers when overriding 'public' inherited member 'System.Collections.ArrayList.Add(object)'

    I want that only MyObject objects can be included in my custom collection.

    Any solution? Thanks!
    Monday, November 13, 2006 11:45 AM

Answers

  • The generic collections are what you really want. Look at namespace System.Collection.Generic and use e.g. List<MyObject>.

    If you want to do it on your own, you should aggregate System.Collections.ArrayList, instead of inheriting it. So use a private member variable of that type and use it internally to store objects. Now you can expose methods as you need them. I.e. you can expose Add(MyObject o) without the problem that Add(object o) must be made inaccessible as it is no member of your class, but only the member of a private field of your class.

    --
    SvenC

    Monday, November 13, 2006 12:04 PM

All replies

  • The generic collections are what you really want. Look at namespace System.Collection.Generic and use e.g. List<MyObject>.

    If you want to do it on your own, you should aggregate System.Collections.ArrayList, instead of inheriting it. So use a private member variable of that type and use it internally to store objects. Now you can expose methods as you need them. I.e. you can expose Add(MyObject o) without the problem that Add(object o) must be made inaccessible as it is no member of your class, but only the member of a private field of your class.

    --
    SvenC

    Monday, November 13, 2006 12:04 PM
  • Very nice idea!

    thanks a lot!

    Monday, November 13, 2006 4:09 PM