Reputation: 956
I am currently trying to override the Remove function of the generic List-Class. But I am struggling with one tiny part of my approach - with the reference to an object outside of the Remove-method.
public new void Remove(ref string item)
{
if (Count > 9)
{
Remove(this[0]);
}
base.Remove(item);
}
This method doesnt work because it is not overriding the actual Remove-method.
Does anyone know how to handle this?
EDIT: in the remove function I want to call a method on the reference object.
EDIT2: my current version
class SocketList<WebSocketConnection>
{
private List<WebSocketConnection> theList = new List<WebSocketConnection>();
public void Remove(ref WebSocketConnection obj)
{
obj.Dispose();
theList.Remove(obj);
// additional stuff
}
}
But in this version it is not possible to call the Dispose method on the referenced object. Im getting a message that says that there is no such method available for this object.
EDIT3: This is the Class in which I want to call the Dispose method
public class WebSocketConnection : IWebSocketConnection
{
{...}
// Flag: Has Dispose already been called?
private bool disposed = false;
// Instantiate a SafeHandle instance.
private SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);
{...}
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
handle.Dispose();
// Free any other managed objects here.
//
}
// Free any unmanaged objects here.
//
disposed = true;
}
}
Upvotes: 0
Views: 685
Reputation: 37000
You can´t override any member of List<T>
because non of them is virtual
. Also new
won´t solve this because it simply hides the base-implementation. You may your list as MyExtList<MyClass> a = new MyExtList<MyClass>()
. However whenever you cast this instance to its base-class also the base-implementation is used instead of your "overridden" one.
However you can do the following to achieve what you really want:
class MyExtList<T>
{
private List<T> theList = new List<T>();
public void Remove(T obj)
{
theList.Remove(obj)
// additional stuff
}
}
Thuse you won´t even need inheritance of List<T>
but use a compoisition which gives you much more flexibility on what you offer to the user of your class. With your current implementation the user could do everything with the list what he could do with the generic List-implementation also. However in most situation you´re just interested in providing a few methods instead of all. So you can nicely hide everything you won´t provide to the outside by making a completely new class that uses List<T>
instead of deriving from it.
Upvotes: 4