I was searching this on the internet and with no success. So hopefully someone here can answer me this because I don't understand the point of it.
- Is it just good practice or it actually does something?
- Why should I bother if .NET has very good garbage collector?
Example
In this example I will use super-simple data-annotation validation filter. What is the benefit of encapsulating my data context in using
?
public static ValidationResult ValidateUniqueUsername(string username, object context)
{
using (var db = new MainDataContext()) // What's the point?
{
var user = db.Users.SingleOrDefault(x => x.Username == username);
if (user == null) return ValidationResult.Success;
return new ValidationResult("Username already taken");
}
}