﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RefCountable.cs" company="Microsoft Corporation">
//   Copyright (c) 2008, 2009, 2010 All Rights Reserved, Microsoft Corporation
//
//   This source is subject to the Microsoft Permissive License.
//   Please see the License.txt file for more information.
//   All other rights reserved.
//
//   THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
//   KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//   IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//   PARTICULAR PURPOSE.
// </copyright>
// <summary>
//   Provides a base class for reference counting classes.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Exchange.Data.Internal
{
    using Strings = CtsResources.SharedStrings;

    /// <summary>
    /// Provides a base class for reference counting classes.
    /// </summary>
    internal abstract class RefCountable
    {
        /// <summary>
        /// The reference count.
        /// </summary>
        private int refCount;

        /// <summary>
        /// Initializes a new instance of the <see cref="RefCountable"/> class.
        /// </summary>
        protected RefCountable()
        {
            this.refCount = 1;
        }

        // Orphaned WPL code.
#if false
        /// <summary>
        /// Gets the reference count.
        /// </summary>
        /// <value>The reference count.</value>
        public int RefCount
        {
            get
            {
                return this.refCount;
            }
        }
#endif

        /// <summary>
        /// Adds a reference count.
        /// </summary>
        public void AddRef()
        {
            int rc = System.Threading.Interlocked.Increment(ref this.refCount);
            InternalDebug.Assert(rc > 1);
        }

        /// <summary>
        /// Removes a reference count and, if the reference count is zero calls <see cref="Destroy"/>.
        /// </summary>
        public void Release()
        {
            int rc = System.Threading.Interlocked.Decrement(ref this.refCount);
            InternalDebug.Assert(rc >= 0);
            if (rc == 0)
            {
                this.Destroy();
            }
        }

        /// <summary>
        /// Destroys this instance.
        /// </summary>
        protected virtual void Destroy()
        {
        }
    }
}