Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can TcpClient implement IDisposable and not have a public Dispose method?

Just as the title says:

How can TcpClient implement IDisposable and not have a public Dispose method?

like image 742
CannibalSmith Avatar asked Feb 24 '10 11:02

CannibalSmith


People also ask

Does not implement IDisposable Dispose?

If an object doesn't implement IDisposable , then you don't have to dispose of it. An object will only expose Dispose if it needs to be disposed of.

What is IDisposable interface in C implement the Dispose method?

The Dispose method is automatically called when a using statement is used. All the objects that can implement the IDisposable interface can implement the using statement. You can use the ildasm.exe tool to check how the Dispose method is called internally when you use a using statement.

Why we need to implement Dispose method while we have option to implement destructor?

Because you can't control when (or even if) the GC calls Finalize, you should treat destructors only as a fallback mechanism for releasing unmanaged resources. Instead, the approved way to release unmanaged resources is to make your class inherit from the IDisposable interface and implement the Dispose() method.

Which of these are the reason for implementing IDisposable interface?

If your class creates unmanaged resources, then you can implement IDisposable so that these resources will be cleaned up properly when the object is disposed of. You override Dispose and release them there.


2 Answers

By using explicit interface implementation. Instead of

public void Dispose()
{
    ...
}

it would have

void IDisposable.Dispose()
{
    ...
}

Various other types do this; sometimes it's out of necessity (e.g. supporting IEnumerable.GetEnumerator and IEnumerable<T>.GetEnumerator) and at other times it's to expose a more appropriate API when the concrete type is known.

like image 127
Jon Skeet Avatar answered Sep 18 '22 13:09

Jon Skeet


See explicit interface implementation. You need to explicitly cast the instance of TcpClient to IDisposable, or wrap it in a using() {...} block. Note that classes that implement IDisposable explicitly often provide a public Close() method instead

like image 39
thecoop Avatar answered Sep 20 '22 13:09

thecoop