C# 2.0 and C++/CLI Event
Book list on bookpool

C++/CLI, IDisposable and Finalize

With Beta 2, C++/CLI changed the code that is generated with the destructor (~Class) and the explicit finalize (!Class). It's a great improvement! Now the Dispose(true) pattern for embedded objects is implemented with this code that just contains a destructor and a explicit finalize:

ref class Resource
{
public:
  ~Resource() // IDisposable
  {
    // release resource
  }

protected:
  !Resource() // Finalize
  {
    // release resource
  }

};

The result of this C++/CLI code not only implements the IDisposable interface and overrides the Finalize method (as it happened with earlier releases), but also implements Dispose(true) as can be verified with the IL code:

ref class Resource : IDisposable
{
public:
  void Dispose()
  {
    Dispose(true);
    GC.SupressFinalize(true);
  }
private:

  ~Resource()
  {
    // release resource
  }
internal:
  void Dispose(bool disposing)
  {
    if (disposing)
      ~Resource();
    else
    {
      try
      {
        !Resource();
      }
      finally
      {
        Object::Finalize();
      }
    }
  }
internal:
  void Finalize()
  {
    Dispose(false);
  }
private:
  !Resource()
  {

  }

};

It would be great to have such a feature with C#.

Christian

Comments

Feed You can follow this conversation by subscribing to the comment feed for this post.

Joe Duffy

Would imagine you've seen this: http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=88e62cdf-5919-4ac7-bc33-20c06ae539ae... has a lot of annotations from Herb, the architect responsible for the new C++/CLI dispose/finalize design. Couldn't agree with you more--1st class support for Dispose in either C# or the runtime would be awesome.

Christian

Joe, thanks for the link. It's a great article!

The comments to this entry are closed.