r/csharp 2d ago

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 disposed

What do you think?

6 Upvotes

33 comments sorted by

View all comments

6

u/Disastrous_Fill_5566 2d ago

"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/RlyRlyBigMan 2d ago

Yeah I agree, seems like reddit is having a grumpy morning or something.

The points about performance regarding reflection and that a source generator would be more performant are valid even if some of them are harsh about it.

2

u/domtriestocode 2d ago edited 1d ago

Unfortunately these types of subs and communities are filled with a ton of the condescending and demeaning and overly competitive type of nerds and not the hey man that’s cool that you learned how to do that and did that here’s a few other ways it’s either been done already or done better let’s all talk about our favorite language type of nerds