1

Usually I use the pattern described in this question:

SqlConnection SqlCommand SqlDataReader IDisposable

That looks like this:

using (var conn = new SqlConnection(lewtanConnStr))
using (var cmd = new SqlCommand(sql, conn)) 
{
    try
    { 
        await conn.OpenAsync();
        using(reader = await cmd.ExecuteReaderAsync())

However, on the MSDN/Microsoft website usually only SqlConnection is wrapped in a using block. Is it good enough to just dispose SqlConnection? (Sometimes even SqlConnection just calls close() without wrapping it in using).

The code examples on this article are one instance:

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
ca9163d9
  • 27,283
  • 64
  • 210
  • 413
  • 2
    Any type that implements `IDisposable` should really have a `using` block to go with it. That said, it's questionable if `SqlCommand` really needed to implement `IDisposable` in the first place. In VB.Net it's harder to stack `using` blocks like that, and it's common to see a pattern that "fakes" it, where the `SqlCommand` might not be properly disposed. I've never seen this cause a problem. `SqlDataAdapter` is similar. It doesn't really need `IDisposable` on it's own, except that is sometimes wraps `SqlConnection`. – Joel Coehoorn Apr 03 '18 at 15:04
  • And don't get me started on `SqlDataReader`, which isn't documented as closing the reader in it's `Dispose()` method. – Joel Coehoorn Apr 03 '18 at 15:09
  • The question is why MSDN examples only dispose `SqlConnection`? – ca9163d9 Apr 03 '18 at 15:09
  • 1
    And the answer is because it's "questionable if `SqlCommand` really needed to implement `IDisposable` in the first place." The MSDN examples are one argument it didn't need to implement the interface... but only one argument. The examples were written be real humans, after all, and like all humans those people are fallible. They might be wrong in how they wrote the example, or they might be wrong about how `SqlCommand` uses unmanaged resources. – Joel Coehoorn Apr 03 '18 at 15:11
  • 1
    Personally, my take is whether it needs or not, in the end `SqlCommand` **did** implement `IDisposable`, and so as programmer using that type I should respect it. But I also occasionally need to work in VB.Net, and in those situation I've used the "fake" pattern that can leave the `SqlCommand` hanging. – Joel Coehoorn Apr 03 '18 at 15:14
  • Many Objects implement `IDisposable` solely because they are derived from `System.ComponentModel.Component` which allows them to be placed in the Winform designer. – TnTinMn Apr 03 '18 at 16:32
  • Another duplicate: [Does ADO.NET go overboard with IDisposable?](https://stackoverflow.com/questions/49350749/does-ado-net-go-overboard-with-idisposable) – Zohar Peled Apr 03 '18 at 18:42

0 Answers0