yet another topic on the subject as I got tired of reading countless topics to find an answer to my questions :)
Lets say we have the following class:
public class MyClass
{
private const string conString = "connection string";
private int Operation()
{
int count = 0;
using(var con = SqlConnection(conString))
{
string select_cmd = "SELECT * FROM TABLE";
using(var cmd = new SqlCommand(select_cmd, con))
{
using(var reader = cmd.ExecuteReader())
{
while(reader != null && reader.Read())
count++;
}
}
}
return count;
}
}
Since the connection to the database is instantiated inside a using statement thus the con.close() and eventually con.dispose() methods will be called, is there a need to implement IDisposable for MyClass? Will MyClass get garbage-collected when it goes out of scope?
EDIT:
Thank you for your replies, thats what I thought but I needed to make it clear. One more question.
If my class has several Operations() that do some work on a database, is it a better practice from a resources consumption point of view to have a SqlConnection member, instanciate and open it on the class constructor and implement IDisposable to close it instead of using "using" statements in each operation (opening and closing the database on each operation) ? Ofcourse that way I should only instantiate and use the MyClass object in using statements.