How to implement IDisposable Design Pattern in C#?

We should use an IDisposable design pattern (or Dispose Pattern) when we need to dispose of unmanaged objects.

For implementing the IDisposable design pattern, the class which deals with unmanaged objects directly or indirectly should implement the IDisposable interface.And implement the method Dispose declared inside of the IDisposable interface. We do not directly deal with unmanaged objects. But we deal with managed classes, which deals directly with unmanaged objects. For example, File handlers, connection string, HTTP streams, etc.

Important aspect of this pattern is that it makes easier for inherited classes to follow the IDisposable design pattern. And it is because of the implementation of an overridable Dispose method. This pattern also suggests the use of the Finalizer method (or destructor in c#). However, if we use the Finalizer, it should be managed properly due to its performance implications.


static class Program {
   static void Main(string[] args) {
      using var serviceProxy = new ServiceProxy(null);
public class ServiceProxy : System.IDisposable {
   private readonly HttpClient httpClient;
   private bool disposed;

   public ServiceProxy(IHttpClientFactory httpClientFactory) {
      httpClient = httpClientFactory.CreateClient();
   ~ServiceProxy() {
   public void Dispose() {
   protected virtual void Dispose(bool disposing) {
      if (disposed) {

      if (disposing) {
         // Dispose managed objects
      // Dispose unmanaged objects
      disposed = true;
   public void Get() {
      var response = httpClient.GetAsync("");
   public void Post(string request) {
      var response = httpClient.PostAsync("", new StringContent(request));