-1

I have a bunch of methods that do the following:

using(var cn = new Connection())
{
    //custom code
}

Is there a way I can still use the using, but just call my custom code?

xaisoft
  • 3,343
  • 8
  • 44
  • 72
  • 2
    i really don't know what you are trying to achieve... what is your custom code? – stefankmitph Mar 14 '15 at 18:47
  • @stefankmitph - I didn't think that his small sample was that hard to understand. `Custom code` just meant that I had multiple methods with identical using statements but the code between them was the only thing different. – xaisoft Mar 15 '15 at 04:53

2 Answers2

2

What about creating a new method encapsulating your using-block and putting an action-delegate in?

static void Main(string[] args)
{
    doCustomCode(() =>
    {
        Console.WriteLine("customCode #1");
    });

    doCustomCode(() =>
    {
        Console.WriteLine("customCode #2");
    });
}

private static void doCustomCode(Action action)
{
    using (var con = new Connection())
    {
        action();
    }
}

In case you need somethig more specific than a simple action, just modifiy the according parameter.

Pilgerstorfer Franz
  • 8,303
  • 3
  • 41
  • 54
  • I had a feeling it might be something like this. Is this the typical way or are there other options? Thanks. – xaisoft Mar 15 '15 at 04:54
  • In most cases when I do code I write multiple using statements rather than using my given answer. IMO I don't see that much advantages on using a method like `doCustomCode(..)` – Pilgerstorfer Franz Mar 15 '15 at 06:52
  • I would agree. It is more concise, but I don't think much advantage is gained, plus, it seems like better practice to force the user to explicitly put the using statement. Thanks. – xaisoft Mar 16 '15 at 01:02
0

You can use any of the following:

  1. Wrap your custom code in a method.
  2. Use a try { } finally { }
  3. Aspect-Orientanted-Programming using a Proxy
  4. Use IL editor like PostSharp
Michal Ciechan
  • 13,492
  • 11
  • 76
  • 118