none
Safe COM objects and IDisposable pattern RRS feed

  • Question

  • I've written a quick implementation of the IDisposable pattern.   In this case I'm dealing with the Outlook Application object.

    Wrappers for ActiveExplorer() and GetNameSpace() have been created.

    My Questions:
    - Are there any glaring omissions in the code?
    - Perhaps there is something I can do to make it better (e.g. Using an Abstract class to make it more general purpose)
    - I've read that "SafeHandle" is good to use in the IDisposable pattern.  I'm not entirely sure how it would apply to Office objects, if at all.




    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Outlook = Microsoft.Office.Interop.Outlook;
    
    namespace CompanyLib
    {
        public class MYApplication : IDisposable
        {
    
            private Outlook.Application _app = null;
            private bool _disposed = false;
    
            public MYApplication()
            {
                _app = new Outlook.Application();
            }
    
            // Application Object functions
            public Outlook.NameSpace GetNameSpace()
            {
                if( _app != null)
                {
                    return _app.GetNamespace("MAPI");
                }
                else
                {
                    return null;
                }
            }
    
            public Outlook.Explorer ActiveExplorer()
            {
                if( _app != null)
                {
                    return _app.ActiveExplorer();
                }
                else
                {
                    return null;
                }
            }
    
    
    
            // Public implementation of Dispose pattern callable by consumers.
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
    
            // Protected implementation of Dispose pattern.
            protected virtual void Dispose(bool disposing)
            {
                if (_disposed)
                    return;
    
                if (disposing)
                {
                    // Free any other managed objects here.
                    //
                }
    
                // Free any unmanaged objects here.
                //
                if (_app != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(_app);
                    _app = null;
                }
    
                _disposed = true;
            }
    
            ~EZApplication()
            {
                Dispose(false);
            }
    
        }
    }
    


    Germán Hayles

    Monday, March 18, 2019 8:21 PM

Answers

All replies