0

Instead of doing:

 using(MyDataContext db = new MyDataContext())
 {
   //do something
 }

I'd like to use an Action()

public static class SimpleUsing
{
  public static void DoUsing(Action action)
  {
    using(MyDataContext db = new MyDataContext())
    {
      //do something
    }
  }
}

Which would be used as

SimpleUsing.DoUsing(() =>
{
   //but how to get DataContext variable?
}

The main issue is how do I access the "db" variable to make use of the DataContext?

4thSpace
  • 43,672
  • 97
  • 296
  • 475

1 Answers1

7

The generic types Action<T1>, Action<T1, T2>, etc. define a delegate which takes some arguments. So you can write it like this:

public static class SimpleUsing
{
    public static void DoUsing(Action<MyDataContext> action)
    {
        using (MyDataContext db = new MyDataContext())
           action(db);
    }

    public static T DoUsing(Func<MyDataContext, T> fn)
    {
        using (MyDataContext db = new MyDataContext())
           return fn(db);
    }
}

// ...

SimpleUsing.DoUsing(db => {
    // do whatever with db
});

var result = SimpleUsing.DoUsing(db => {
    return 42; // uses Func overload, result will be 42
});
mqp
  • 70,359
  • 14
  • 95
  • 123
  • Excellent. Thanks. Do you know how I may be able to return a type from this? That makes DoUsing a generic method (return some T). – 4thSpace Nov 11 '11 at 19:39
  • I believe you have to use a Func<> to return a value. – TGnat Nov 11 '11 at 20:00
  • @TGnat, do you have some idea what that looks like? It will have to come out of action and pass back to the method. – 4thSpace Nov 11 '11 at 20:12