Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 504
Robert Avatar asked Jan 17 '26 20:01

Robert


2 Answers

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...
}
like image 83
Mark Byers Avatar answered Jan 20 '26 12:01

Mark Byers


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)

like image 37
Amittai Shapira Avatar answered Jan 20 '26 12:01

Amittai Shapira