Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using with object type

I try to write the following code and get an error

using (object obj = await command.ExecuteScalarAsync())
{
   //....
}

Implicitly convertible to System.IDisposable

How to solve that? I tried the cast (the static one doesn't work...)
If I don't use using and check that the object is not null I do the casting in the following way:

Convert.ToInt32(obj);

But I should use using

like image 926
Yakov Avatar asked Sep 22 '26 19:09

Yakov


2 Answers

You don't need to dispose in this case, simply do:

object obj = await command.ExecuteScalarAsync();

ExecuteScalarAsync returns a Task<T>, which you are subsequently awaiting. This "awaiting" will handle the task object, you get the result from the task/execution, which is very unlikely to require disposal.

like image 192
Lasse V. Karlsen Avatar answered Sep 24 '26 09:09

Lasse V. Karlsen


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;
}
like image 40
Luaan Avatar answered Sep 24 '26 09:09

Luaan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!