Dispose method does not allow the object to participate in the using in C#. Why?
According to the CLR via C#:
If a dynamic expression is specified as the collection in a foreach statement or as a resource in a using statement, the compiler will generate code that attempts to cast the expression to the non-generic System.IEnumerable interface or to the System.IDisposable interface, respectively. If the cast succeeds, the expression is used and the code runs just fine. If the cast fails, a Microsoft.CSharp.RuntimeBinder.RuntimeBinderException exception is thrown.
So, I am trying the following:
using System;
namespace myprogram
{
delegate void VoidRes();
class Program
{
static void Main(string[] args)
{
dynamic a = new
{
Dispose = new VoidRes
(
delegate () { Console.WriteLine("in Dispose"); }
)
};
using(a) {
Console.WriteLine("foo");
}
}
}
}
And I am getting an error:
Unhandled exception. Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot implicitly convert type '<>f__AnonymousType4' to 'System.IDisposable' at CallSite.Target(Closure , CallSite , Object ) at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
That is strange, because I thought that in order to satisfy the IDisposable
interface it is enough to implement the Dispose
method (exactly what I did in my anonymous type).
What am I missing here?