2

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

5 Answers 5

6

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...
}
Sign up to request clarification or add additional context in comments.

1 Comment

"other methods should remain unchanged": that means that in this incapsulation case you, like a developer, should map all List implementations too. Only for having one Add() customized method IMHO seems a luxury.
2

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)

Comments

1

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

Comments

0

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.
    }
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.