Using statement is only valid (and useful) with IDisposable
objects. It gives you nothing if your object is not disposable. Basically, it's syntactic sugar for this equivalent code:
IDisposable obj = ...;
try
{
...
}
finally
{
obj.Dispose();
}
The guys implementing the C# compiler simply decided that having the using
statement available for classes that don't implement IDisposable
would be useless and confusing.
It doesn't work in any way as with
or some other statement that looks superficially similar. It will not affect garbage collection in any way (apart from perhaps limiting variable scope - but simple blocks ({ ... }
) to the very same thing.
Safely getting the value is something completely different. You want to do something like this:
object val = await command.ExecuteScalarAsync();
if (val == DBNull.Value)
{
// It's null
}
else
{
int realValue = (int)val;
}