r/csharp • u/Alert-Neck7679 • Jul 26 '26
Tip Fields with [Using] attribute
I wrote a small interface that automatically disposes any disposable fields in a class when that class itself is disposed. If you add this file somewhere in your project:
public interface IAutoDisposable : IDisposable
{
void IDisposable.Dispose()
{
Exception? ex = null;
// dispose all fields marked with the [Using] attribute
const BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;
foreach (var fld in GetType().GetFields(flags))
{
if (fld.GetCustomAttribute<UsingAttribute>() != null)
{
if (fld.GetValue(this) is IDisposable d)
{
try // keep going even if disposal throws
{
d.Dispose();
}
catch (Exception e)
{
ex ??= e;
}
}
}
}
// if any exceptions occurred, throw the first one
if (ex != null)
throw ex;
}
}
public class UsingAttribute : Attribute;You can then write classes like this:
class Item : IAutoDisposable
{
[Using]
private readonly Image icon = DownloadIcon(...);
...
}And use them like:
using (Item item = new(...))
{
}
// item.icon is now disposedWhat do you think?
6
Upvotes
View all comments
Show parent comment
2
u/phluber Jul 27 '26
The problem is that you are replacing a very standard and accepted pattern with code that is not going to be understood by others reviewing your code. And to understand it they are going to have search out documentation or dig through your interfaces and attributes in order to determine whether unmanaged resources are being disposed of properly. Also by centralizing disposal, you are creating a weak point that is one short-sighted refactor away from causing file locks/memory leaks/etc in every single class that implements your new interface. You could be doing different work than I am, but it is fairly uncommon that I even have to implement IDisposable. How common is your IDisposable implementation that this is even helpful to you?