Search code examples
c#dynamicusing

"using" block together with "dynamic"


If I write

using (dynamic d = getSomeD ()) {
   // ...
}

does that mean that d.Dispose () is called when the using block is left?

What happens when d does not implement IDisposable?


Solution

  • does that mean that d.Dispose () is called when the using block is left?

    Yes. If the type implements IDisposable then Dispose will be called.

    What happens when d does not implement IDisposable?

    You will get an exception

    An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll
    Cannot implicitly convert type 'YourType' to 'System.IDisposable'. An explicit conversion exists (are you missing a cast?)

    You can try that yourself by having a class like:

    class MyDisposable : IDisposable //Remove IDisposable to see the exception
    {
        public void Dispose()
        {
            Console.WriteLine("Dispose called");
        }
    }
    

    and then:

    using (dynamic d = new MyDisposable())
    {
    
    }