Robert
Robert

Reputation: 2691

Customized list in C#

I want to create customized list in c#. In my customized list I want only create customized function Add(T), other methods should remain unchanged.

When I do:

public class MyList<T> : List<T> {}

I can only overide 3 functions: Equals, GetHashCode and ToString.

When I do

public class MyList<T> : IList<T> {}

I have to implement all methods.

Thanks

Upvotes: 2

Views: 188

Answers (5)

Mark Byers
Mark Byers

Reputation: 837926

When I do public class MyList : IList {}

I have to implement all methods.

Yes, but it's easy... just send the call to the original implementation.

class MyList<T> : IList<T>
{
    private List<T> list = new List<T>();

    public void Add(T item)
    {
        // your implementation here
    }
    
    // Other methods

    public void Clear() { list.Clear(); }
    // etc...
}

Upvotes: 6

Tigran
Tigran

Reputation: 62248

You can another thing again, by using new keyword:

public class MyList<T> : List<T> 
{
   public new void Add(T prm) 
   {
       //my custom implementation.
   }
}

Bad: The thing that you're restricted on use only of MyList type. Your customized Add will be called only if used by MyList object type.

Good: With this simple code, you done :)

Upvotes: 1

user586399
user586399

Reputation:

Use a private List<T> rather than inheritance, and implement your methods as you like.

EDIT: to get your MyList looped by foreach, all you want is to add GetEnumerator() method

Upvotes: 0

Anders Abel
Anders Abel

Reputation: 69250

You could use the decorator pattern for this. Do something like this:

public class MyList<T> : IList<T>
{
    // Keep a normal list that does the job.
    private List<T> m_List = new List<T>();

    // Forward the method call to m_List.
    public Insert(int index, T t) { m_List.Insert(index, t); }

    public Add(T t)
    {
        // Your special handling.
    }
}

Upvotes: 0

Amittai Shapira
Amittai Shapira

Reputation: 3827

You can have MyList to call List<T> implementation inetrnally, except for Add(T), you'd use Object Composition instead of Class Inheritence, which is also in the preface to the GOF book: "Favor 'object composition' over 'class inheritance'." (Gang of Four 1995:20)

Upvotes: 2

Related Questions