Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PetaPoco.Database implements IDisposable, so why don't most examples have a 'using' statement?

The PetaPoco.Database object implements IDisposable but I rarely if ever see code samples (including on PetaPoco's own website) that include a using statement as follows:

using (var db = new Database("MyConnectionString"))
{
    // Do database stuff
}

Most often I simply see:

var db = new Database("MyConnectionString");
// Do database stuff
// I never see .Dispose() called.

How should PetaPoco.Database objects actually be handed?

like image 201
Howiecamp Avatar asked Oct 30 '15 20:10

Howiecamp


People also ask

When should you use IDisposable?

If you access unmanaged resources (e.g. files, database connections etc.) in a class, you should implement IDisposable and overwrite the Dispose method to allow you to control when the memory is freed.

Does using statement Call dispose?

The using declaration calls the Dispose method on the object in the correct way when it goes out of scope. The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned.

What is using in asp net?

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.


2 Answers

As a simple rule: if a class implements IDisposable then go ahead and wrap it in a using. They may not actually be using any unmanaged resources, but it won't hurt and might future-proof you against changes.

like image 104
STW Avatar answered Nov 01 '22 10:11

STW


PetaPoco maintainer here. Dispose is the same as calling CloseSharedConnection(). However, c# syntax only supports using(...) with IDisposable. For instance IDBConnection, from memory, supports both Close and Dispose.

Basically, it boils down to choice

Example 1

using(var db = new PetaPoco()) 
{
    // some code
}

Example 2

var db = new PetaPoco()

try 
{
    // code
}
finally 
{
    db.CloseSharedConnection();
}
like image 43
Plebsori Avatar answered Nov 01 '22 08:11

Plebsori