Skip to content

Instantly share code, notes, and snippets.

@tcartwright
Created May 14, 2024 15:39
Show Gist options
  • Save tcartwright/dab50ebaff7c59f05013de0fb349cabd to your computer and use it in GitHub Desktop.
Save tcartwright/dab50ebaff7c59f05013de0fb349cabd to your computer and use it in GitHub Desktop.
C#: IsDisposed() Checks to see if an object is disposed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
public static class ObjectExtensions
{
public static bool IsDisposed(this IDisposable obj)
{
/*
TIM C: This hacky code is because MSFT does not provide a standard way to interrogate if an object is disposed or not.
I wrote this based upon streams, but it should work for many other types of MSFT objects (maybe).
*/
if (obj == null) { return true; }
var objType = obj.GetType();
//var foo = new System.IO.BufferedStream();
// the _disposed pattern should catch a lot of msft objects.... hopefully
var isDisposedField = objType.GetField("_disposed", BindingFlags.NonPublic | BindingFlags.Instance) ??
objType.GetField("disposed", BindingFlags.NonPublic | BindingFlags.Instance);
if (isDisposedField != null) { return Convert.ToBoolean(isDisposedField.GetValue(obj)); }
isDisposedField = objType.GetField("_isOpen", BindingFlags.NonPublic | BindingFlags.Instance);
if (isDisposedField != null) { return !Convert.ToBoolean(isDisposedField.GetValue(obj)); }
// System.IO.FileStream
var strategyField = objType.GetField("_strategy", BindingFlags.NonPublic | BindingFlags.Instance);
if (strategyField != null)
{
var strategy = strategyField.GetValue(obj);
var isClosedField = strategy.GetType().GetProperty("IsClosed", BindingFlags.NonPublic | BindingFlags.Instance);
if (isClosedField != null) { return Convert.ToBoolean(isClosedField.GetValue(strategy)); }
}
// other streams that use this pattern to determine if they are disposed
if (obj is Stream stream) { return !stream.CanRead && !stream.CanWrite; }
return false;
}
}
@tcartwright
Copy link
Author

Sometimes, for whatever reason you need to check if an object is disposed. Well, there is no built in way to do that. So this mess was written against the Stream objects. The _disposed should catch a LOT of msft objects, but I am betting there are even weirder patterns out there.

Good luck using this code, YMMV

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment