Are there any side effects of returning from inside a using() statement?

前端 未结 5 1327
一向
一向 2021-01-31 07:02

Returning a method value from inside a using statement that gets a DataContext seems to always work fine, like this:

public sta         


        
5条回答
  •  伪装坚强ぢ
    2021-01-31 07:10

    No, I think it's clearer this way. Don't worry, Dispose will still be called "on the way out" - and only after the return value is fully evaluated. If an exception is thrown at any point (including evaluating the return value) Dispose will still be called too.

    While you certainly could take the longer route, it's two extra lines that just add cruft and extra context to keep track of (mentally). In fact, you don't really need the extra local variable - although it can be handy in terms of debugging. You could just have:

    public static Transaction GetMostRecentTransaction(int singleId)
    {
        using (var db = new DataClasses1DataContext())
        {
            return (from t in db.Transactions
                    orderby t.WhenCreated descending
                    where t.Id == singleId
                    select t).SingleOrDefault();
        }
    }
    

    Indeed, I might even be tempted to use dot notation, and put the Where condition within the SingleOrDefault:

    public static Transaction GetMostRecentTransaction(int singleId)
    {
        using (var db = new DataClasses1DataContext())
        {
            return db.Transactions.OrderByDescending(t => t.WhenCreated)
                                  .SingleOrDefault(t => t.Id == singleId);
        }
    }
    

提交回复
热议问题