-4

I am trying to implement IDisposable in a sample program. If I use SqlConnection class inside a using block statement, it will automatically dispose it.

public int testCon()
{
    using (SqlConnection conn = new SqlConnection("Conn string"))
    {
        using (SqlCommand cmd = conn.CreateCommand())
        {
            conn.Open();
            cmd.CommandText = "SELECT COUNT(1) FROM Carsd";

            return (int)cmd.ExecuteScalar();
        }
    }
}

I have created a class and implemented IDisposable. I have created a new instance inside a using block statement.

class Program 
{
    static void Main(string[] args)
    {
        testDispose objTestDispose;

        using (objTestDispose = new testDispose())
        {
            objTestDispose.UserName = "testUser";
            objTestDispose.PassWord = "testPassword";                                
        }

        Console.WriteLine("Check obj of testDispose Class" + objTestDispose.UserName);
        Console.WriteLine("Check obj of testDispose Class" + objTestDispose.PassWord);
        Console.ReadLine();

    }        
}

public class testDispose : IDisposable
{
    public string UserName { get; set; }
    public string PassWord { get; set; }

    public void Dispose()
    { }              
}

I believe, using block automatically call dispose method. So, if I am create a new instance in using block, it would be dispose after existing using block. But, still I am able to access objTestDispose object outside of the using block.WHY?

Please suggest.

UDPATE

Mr.BWA..Thank you for the making my question duplicate. but you should know I am a student and learning. I have this question in my mind so I have asked here. **You can not say that IDisposable interface only for unmanaged resources.**I can also remove managed resources. It depends on the situation. As per the below link -

What if your object has allocated a 250MB System.Drawing.Bitmap (i.e. the .NET managed Bitmap class) as some sort of frame buffer? Sure, this is a managed .NET object, and the garbage collector will free it. But do you really want to leave 250MB of memory just sitting there – waiting for the garbage collector to eventually come along and free it? What if there's an open database connection? Surely we don't want that connection sitting open, waiting for the GC to finalize the object.

If the user has called Dispose() (meaning they no longer plan to use the object) why not get rid of those wasteful bitmaps and database connections?

So now we will:

get rid of unmanaged resources (because we have to), and get rid of managed resources (because we want to be helpful)

Community
  • 1
  • 1
KiddoDeveloper
  • 568
  • 2
  • 11
  • 34
  • 1
    Because you declare it outside the using block. It doesn't magically disappear. – stuartd Sep 14 '16 at 08:35
  • Even if you declare something outside a `using (SqlConnection conn = new SqlConnection("Conn string"))` it will exist afterwards, as many others are also posting. – Keyur PATEL Sep 14 '16 at 08:37
  • 1
    Have you read [this](http://stackoverflow.com/questions/13988334/difference-between-destructor-dispose-and-finalize-method), [this](http://stackoverflow.com/questions/339063/what-is-the-difference-between-using-idisposable-vs-a-destructor-in-c) or [this](http://stackoverflow.com/questions/456213/destructor-vs-idisposable)? – Tim Schmelter Sep 14 '16 at 08:38
  • 1
    Disposed != Garbage-collected – H H Sep 14 '16 at 09:49
  • Don't confuse the issue in your update - no-one said `IDisposable` was **only** for unmanaged resources and not managed. Of course it can be used for both if you want. As I said, it is contractually agreed that Dispose() will be called, so this is the most efficient way of disposing of unmanaged resources. If you want to do other things inside `Dispose()` then so be it. – slugster Sep 14 '16 at 14:20
  • Thank you Slugster for your reply. I am still trying to understand it. – KiddoDeveloper Sep 14 '16 at 14:33

3 Answers3

2

Dispose is being called, but it doesn't do anything to destroy the object itself (you'll note that a lot of IDiposable classes within the Framework additionally have a IsDisposed property to indicate whether the unmanaged resources have been released or not)

Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166
2

You are still able to access it because you defined it outside the scope of the using block and because you haven't set it to null.

Note that using doesn't set the object to null, it simply means that your Dispose() method will be called, this gives you a contractually guaranteed way to dispose of any unmanaged resources that would otherwise not be cleaned up by the garbage collector.

You should also consider the logic of your statement:

I believe, using block automatically call dispose method. So, if I am create a new instance in using block, it would be dispose after existing using block.

... how could an object set it's own self to null?

slugster
  • 49,403
  • 14
  • 95
  • 145
  • Sir. Could you please tell me how I can testDispose object in a code. It would be helpful for me. – KiddoDeveloper Sep 14 '16 at 09:00
  • Dispose() is actually much more useful for disposing _managed_ resources. – H H Sep 14 '16 at 09:51
  • @Mohit `objTestDispose` will be automatically (in most cases) be cleared up by the garbage collector at some stage once it has gone out of scope (in your case, it goes out of scope once Main() is finished, but that is also coincidentally the end of the application as well). Go and have a good read of the information in the linked question, it covers what the implementation of `IDisposable` is for. – slugster Sep 14 '16 at 14:13
1

From MSDN

IDisposable Interface

Provides a mechanism for releasing unmanaged resources.

The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams. Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.

This is used for release umnamaged resources not for destroy object itself.

BWA
  • 5,672
  • 7
  • 34
  • 45