c# when is dispose called code example
Example 1: dispose method in c# with example
using System;
class DerivedClass : BaseClass
{
bool _disposed = false;
~DerivedClass() => Dispose(false);
protected override void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
}
_disposed = true;
base.Dispose(disposing);
}
}
Example 2: dispose method in c# with example
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
public class DisposableStreamResource2 : DisposableStreamResource
{
protected const uint GENERIC_WRITE = 0x40000000;
protected const uint OPEN_ALWAYS = 4;
[DllImport("kernel32.dll")]
protected static extern bool WriteFile(
SafeFileHandle safeHandle, string lpBuffer,
int nNumberOfBytesToWrite, out int lpNumberOfBytesWritten,
IntPtr lpOverlapped);
private bool _disposed = false;
private bool _created = false;
private SafeFileHandle _safeHandle;
private readonly string _fileName;
public DisposableStreamResource2(string fileName) : base(fileName) => _fileName = fileName;
public void WriteFileInfo()
{
if (!_created)
{
_safeHandle = CreateFile(
@".\FileInfo.txt", GENERIC_WRITE, 0, IntPtr.Zero,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
_created = true;
}
string output = $"{_fileName}: {Size:N0} bytes\n";
_ = WriteFile(_safeHandle, output, output.Length, out _, IntPtr.Zero);
}
protected override void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
_safeHandle?.Dispose();
}
_disposed = true;
base.Dispose(disposing);
}
}
Example 3: dispose method in c# with example
public sealed class Foo : IDisposable
{
private readonly IDisposable _bar;
public Foo()
{
_bar = new Bar();
}
public void Dispose()
{
_bar?.Dispose();
}
}