Search code examples
c#castingidisposableusing-statement

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


Solution

  • 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.