Search code examples
c#.netusing

How to ensure the use tag using in C#


Is there any way to ensure that a class will always be used as a using instead of being instantiated normally

Desired way using(var db = new DbContext()) {}

Common way var db = new DbContext();

I'd like somehow to prevent instantiating the common form. I already know that to use the 'using' it is necessary to implement IDisposable


Solution

  • No, you cannot.


    However, if that is an option, you can write methods that ensure that nobody has to even instantiate your object and make mistakes disposing it:

    For example:

    var instance = new YourObject();
    
    var result = instance.MethodCallNeeeded(17);
    
    // oops, no .Dispose called, basic mistake
    

    How about another way of offering your functionality to your users:

    public static TResult UseYourObject<T>(Func<YourObject, TResult> func)
    {
        using(var x = new YourObject())
            return func(x);
    }
    

    Providing only this method means people cannot forget the using because they are not responsible for creation and disposing of the object.

    Usage would be:

    var result = ClassName.UseYourObject(instance => instance.MethodCallNeeeded(17));
    

    And as the perhaps best option: do code reviews and static code analysis with your juniors. Teach them how to do this. That's why they are juniors.