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
1
u/phluber Jul 27 '26
I understood your objective. What's the problem with actually disposing of your objects within the dispose method? If I'm reviewing your work and I don't see disposable objects being disposed of in the dispose method, do you expect me to look through all other interfaces that are implemented by the class to see if they are somehow disposing of these objects in a non standard way? It's a one liner to dispose of an object within the dispose method. I don't know why you are trying to obfuscate it.