I was doing a quick demo to show dispose in a using bracket, but somehow managed to confuse myself. Here is my simple test:
public class CommonSqlObject : IDisposable
{
public SqlDataReader Reader { get; set; }
public SqlCommand Command { get; set; }
public void Dispose()
{
if (Reader != null)
{
Reader.Close(); // <- too easy to forget
Reader.Dispose(); // <- too easy to forget
}
if (Command != null)
{
Command.Dispose(); // <- too easy to forget
}
}
}
public class Program
{
static void Main(string[] args)
{
test();
}
public static void test()
{
using (CommonSqlObject obj = new CommonSqlObject())
{
SqlCommand cmd = new SqlCommand("hello");
SqlConnection conn = new SqlConnection("data source=some server;initial catalog=somedb;user id=someuser;Min Pool Size=25;Max Pool Size=300;TimeOut=30;TransparentNetworkIPResolution=False;TrustServerCertificate=true");
cmd.Connection = conn;
obj.Command = cmd;
var SqlDataReader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
obj.Reader = SqlDataReader;
}
}
}
Basically it is a fake server and I didn't open connection, so exception will be thrown in this console app. I thought if I put a break point in my Dispose method, my visual studio should hit the breakpoint and then exit the console program.
However, in my vs 2019, it just throws exception and exit, and there is no evidence that my dispose method was indeed triggered (as my breakpoint was not hit). Is this something I am doing wrongly or is it because it is a console app?
The given answer is correct, and to be bit more precise, if this code is in a web app, then in my visual studio, I do see dispose get called. In console, it didn't (as explained in the answer).