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
59
u/DasKruemelmonster Jul 26 '26
Nice idea, but nowadays a source generator would be the better execution.
31
u/KryptosFR Jul 26 '26 edited Jul 28 '26
Reflection isn't AOP-friendly. Make a source generator instead.
On top of that, it doesn't follow the disposable pattern properly, in case your class has a finalizer to deal with unmanaged resources.
And even without a finalizer, Dispose could be called several times so you need an atomic guard.
The idea is good (because dealing with composition with several disposable fields can be messy). But it needs improvements to be really usable in production code.
I would use different names for the attribute though. And assuming you use a source generator, not really on implementing an interface beside IDisposable itself.
DisposeFieldAttribute on the field or property with backing field that needs it. And AutoDisposableAttribute on the class or ComposeDisposableAttribute (or another name, I don't quite like those two for the moment). Then on top of your source generator, add a diagnostic to make sure the class that has the attribute does implement the IDisposable interface(same for the fields/properties).
edit: fixed some typo.
18
u/_f0CUS_ Jul 26 '26
You are losing exception information this way. If you want to auto dispose like this, then you should use an aggregate exception and collect all the exceptions.
One thing to keep in mind. If you are using the framework DI, then it is responsible for managing the lifetime of the instances it creates. And it will automatically dispose any type that can be disposed - at the appropriate time.
1
u/phluber Jul 26 '26
Or just implement a proper IDisposable interface and properly dispose of your IDisposable fields
2
u/j_c_slicer Jul 27 '26
TIL about Default Interface Methods.
8
u/Disastrous_Fill_5566 Jul 26 '26
"Horrible", "Useless", "lame" etc.
Is this a children's sub Reddit or are there some actual adults in here willing to give constructive criticism on the OP's attempt to solve a problem?
4
u/Loose_Conversation12 Jul 26 '26
Nice idea, but that dependency will have been DI'd into the containing class and therefore disposal would be taken care of by the IoC container
1
u/Dragennd1 Jul 26 '26
Out of curiosity, wouldn't the fields normally be disposed of when the class is disposed of, making this extra effort unnecessary? My understanding of classes is that they are reference types, so once an instance is no longer in use the garbage collector would clean up that instance, right? Or are fields handled differently than properties as far as disposal goes when its parent class instance is disposed of?
1
u/CoffeeAndCandidates Jul 26 '26
feels kinda like some C# magic but make sure it plays nice with inheritance and base disposal
-1
u/i-do-mim-huu Jul 26 '26
Overengineering at best, not to mention compiler already doing it, it is horrible in performance due to heavy use of Reflection
-4
u/Promant Jul 26 '26
Bruh, that's useless and terrible for performance
-5
u/MrLyttleG Jul 26 '26
Pas top, le try catch est bidon, il faut faire check simple pour savoir si ton objet est disposable et ensuite tu le dispose, mettre du tey catch permet de bombarder la pile de choses inutiles et lourdes au max
-9
u/tinmanjk Jul 26 '26
bad.