A return statement is the way a function provides that result. There's no other way to do that, so it's not a matter of style; if your function has a useful result, you need a return statement. In some cases, you're only calling a function for its side-effects, and there is no useful result.
In c#, the return statement is useful to terminate the execution of the method in which it appears and returns the control back to the calling method. Generally, in c# the return statement is useful whenever we want to get some value from the other methods.
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);
}
}
Have a look at this
Understanding the 'using' statement in C#
The CLR converts your code into MSIL. And the using statement gets translated into a try and finally block. This is how the using statement is represented in IL. A using statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause.
There are no side effects of returning from inside a using()
statement.
Whether it makes the most readable code is another discussion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With