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!

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment

Your Information

(Name and email address are required. Email address will not be displayed with the comment.)