2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

デザインパターンメモ

Last updated at Posted at 2024-08-07

Dispose

public static class DisposeSample {
    public static void Execute() {
        using (var obj = new DerivedClass()) {
        }
    }

    class BaseClass : IDisposable {
        private bool _disposed = false;

        ~BaseClass() {
            Dispose(disposing: false);
        }

        public void Dispose() {
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing) {
            if (_disposed) return;

            if (disposing)
            {
            }

            Console.WriteLine($"BaseClass.Dispose({disposing});");
            _disposed = true;
        }
    }

    class DerivedClass : BaseClass {
        private bool _disposed = false;

        protected override void Dispose(bool disposing) {
            if (_disposed) return;

            if (disposing)
            {
            }

            Console.WriteLine($"DerivedClass.Dispose({disposing});");
            base.Dispose(disposing);
            _disposed = true;
        }
    }
}

Execute()実行結果

DerivedClass.Dispose(True);
BaseClass.Dispose(True);
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?