0

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

Felipe Saboya
  • 51
  • 1
  • 4
  • 2
    Short anser: no. – rokkerboci Jan 30 '18 at 15:19
  • Sounds like an [xy problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me. Care to elaborate why you would want to do this? – default Jan 30 '18 at 15:20
  • Long answer: you can't, because the using uses the "common way" only, it calls db.Dispose() when you get out of the using block. – rokkerboci Jan 30 '18 at 15:20
  • Thank you. It has some junior developers on staff, and I would like to ensure that it will not be possible to start a context without invoking the dispose method. – Felipe Saboya Jan 30 '18 at 15:24
  • Terrible title, by the way. "ensure the use tag using" doesn't make sense to me. perhaps "How to ensure the user uses the "using" statement in C#" – Wyck Jan 30 '18 at 15:25
  • 3
    Notice that FxCop (built-in into Visual Studio) will trigger a warning/error for non-disposed variables if you set it up: https://msdn.microsoft.com/en-us/library/ms182289.aspx – Camilo Terevinto Jan 30 '18 at 15:26

1 Answers1

0

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.

nvoigt
  • 75,013
  • 26
  • 93
  • 142