WeakReferenceDictionary

Further to the last post on my implementation of a strongly-typed variant of WeakReferemce, I thought it would be apropos to post another utility class surrounding weak references. This one really is more academic than useful considering that one could just stick WeakReference<T> into a regular Dictionary<TKey, TValue> and get almost the same functionality. All this class really does is hide away how we're managing the reference inside the dictionary.

/// <summary>
/// Represents a dictionary that only holds weak references on values stored within it.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.
/// <remarks>This must be a reference type (by definition, there's no reason to have a weak reference on value types).</remarks>
/// </typeparam>
public class WeakReferenceDictionary<TKey, TValue> : IDictionary<TKey, TValue> where TValue : class
{
    private readonly Dictionary<TKey, WeakReference<TValue>> realDictionary;

    /// <summary>
    /// Initializes a new instance of the <see cref="WeakReferenceDictionary"/>
    /// class that is empty, has the default initial capacity, and uses the default
    /// equality comparer for the key type.
    /// </summary>
    public WeakReferenceDictionary()
    {
        this.realDictionary = new Dictionary<TKey, WeakReference<TValue>>();
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="WeakReferenceDictionary"/>
    /// class that is empty, has the specified initial capacity, and uses the default
    /// equality comparer for the key type.
    /// </summary>
    /// <param name="capacity">
    /// The initial number of elements that the <see cref="WeakReferenceDictionar"/>
    /// can contain.
    /// </param>
    /// <exception cref="System.ArgumentOutOfRangeException">
    /// <paramref name="capacity"/> is less than <c>0</c>.
    /// </exception>
    public WeakReferenceDictionary(int capacity)
    {
        this.realDictionary = new Dictionary<TKey, WeakReference<TValue>>(capacity);
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="WeakReferenceDictionary"/>
    /// class that is empty, has the default initial capacity, and uses the specified
    /// <see cref="System.Collections.Generic.IEqualityComparer" />.
    /// </summary>
    /// <param name="comparer">
    /// The <see cref="System.Collections.Generic.IEqualityComparer" /> implementation to use
    /// when comparing keys, or <c>null</c> to use the default <see cref="System.Collections.Generic.EqualityComparer" />
    /// for the type of the key.
    /// </param>
    public WeakReferenceDictionary(IEqualityComparer<TKey> comparer)
    {
        this.realDictionary = new Dictionary<TKey, WeakReference<TValue>>(comparer);
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="WeakReferenceDictionary" />
    /// class that is empty, has the specified initial capacity, and uses the specified
    /// <see cref="System.Collections.Generic.IEqualityComparer" />.
    /// <param name="capacity">
    /// The initial number of elements that the <see cref="WeakReferenceDictionary" />
    /// can contain.
    /// </param>
    /// <param name="comparer">
    /// The <see cref="System.Collections.Generic.IEqualityComparer<T>" /> implementation to use
    /// when comparing keys, or <c>null</c> to use the default <see cref="System.Collections.Generic.EqualityComparer<T>" />
    /// for the type of the key.
    /// </param>
    /// <exception cref="System.ArgumentOutOfRangeException">
    /// <paramref name="capacity"/> is less than <c>0</c>.
    /// </exception>
    public WeakReferenceDictionary(int capacity, IEqualityComparer<TKey> comparer)
    {
        this.realDictionary = new Dictionary<TKey, WeakReference<TValue>>(capacity, comparer);
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="WeakReferenceDictionary<TKey, TValue>"/>
    /// class that contains elements copied from the specified <see cref="System.Collections.Generic.IDictionary<TKey,TValue>" />
    /// and uses the default equality comparer for the key type.
    /// </summary>
    /// <param name="dictionary">The <see cref="System.Collections.Generic.IDictionary<TKey,TValue>" /> whose elements are
    /// copied to the new <see cref="WeakReferenceDictionary<TKey, TValue>"/>.
    /// </param>
    /// <exception cref="T:System.ArgumentNullException">
    /// <paramref name="dictionary"/> is <c>null</c>.
    /// </exception>
    /// <exception cref="T:System.ArgumentException">
    /// <paramref name="dictionary"/> contains one or more duplicate keys.
    /// </exception>
    public WeakReferenceDictionary(IDictionary<TKey, TValue> dictionary)
    {
        this.realDictionary = new Dictionary<TKey, WeakReference<TValue>>(
            dictionary.ToDictionary(pair => pair.Key, pair => new WeakReference<TValue>(pair.Value)));
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="WeakReferenceDictionary<TKey, TValue>"/>
    /// class that contains elements copied from the specified <see cref="System.Collections.Generic.IDictionary<TKey,TValue>" />
    /// and uses the specified <see cref="System.Collections.Generic.IEqualityComparer<T>" />.
    /// </summary>
    /// <param name="comparer">
    /// The <see cref="System.Collections.Generic.IDictionary<TKey,TValue>" /> whose elements are
    /// copied to the new <see cref="WeakReferenceDictionary<TKey, TValue>"/>.
    /// </param>
    /// <param name="dictionary">
    /// The <see cref="System.Collections.Generic.IEqualityComparer<T>" /> implementation to use
    /// when comparing keys, or <c>null</c> to use the default <see cref="System.Collections.Generic.EqualityComparer<T>" />
    /// for the type of the key.
    /// </param>
    /// <exception cref="System.ArgumentNullException">
    /// <paramref name="dictionary"/> is <c>null</c>.
    /// </exception>
    /// <exception cref="System.ArgumentException">
    /// <paramref name="dictionary"/> contains one or more duplicate keys.
    /// </exception>
    public WeakReferenceDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer)
    {
        this.realDictionary = new Dictionary<TKey, WeakReference<TValue>>(
            dictionary.ToDictionary(pair => pair.Key, pair => new WeakReference<TValue>(pair.Value)),
            comparer);
    }

    #region IDictionary<TKey,TValue> Members

    /// <summary>
    /// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
    /// </summary>
    /// <param name="key">The object to use as the key of the element to add.</param>
    /// <param name="value">The object to use as the value of the element to add.</param>
    /// <exception cref="T:System.ArgumentNullException">
    /// <paramref name="key"/> is null.
    /// </exception>
    /// <exception cref="T:System.ArgumentException">
    /// An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
    /// </exception>
    /// <exception cref="T:System.NotSupportedException">
    /// The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.
    /// </exception>
    public void Add(TKey key, TValue value)
    {
        this.realDictionary.Add(key, new WeakReference<TValue>(value));
    }

    /// <summary>
    /// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key.
    /// </summary>
    /// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</param>
    /// <returns>
    /// true if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key; otherwise, false.
    /// </returns>
    /// <exception cref="T:System.ArgumentNullException">
    /// <paramref name="key"/> is null.
    /// </exception>
    public bool ContainsKey(TKey key)
    {
        return this.realDictionary.ContainsKey(key);
    }

    /// <summary>
    /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
    /// </summary>
    /// <value></value>
    /// <returns>
    /// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
    /// </returns>
    public ICollection<TKey> Keys
    {
        get
        {
            return this.realDictionary.Keys;
        }
    }

    /// <summary>
    /// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
    /// </summary>
    /// <param name="key">The key of the element to remove.</param>
    /// <returns>
    /// true if the element is successfully removed; otherwise, false.  This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>.
    /// </returns>
    /// <exception cref="T:System.ArgumentNullException">
    /// <paramref name="key"/> is null.
    /// </exception>
    /// <exception cref="T:System.NotSupportedException">
    /// The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.
    /// </exception>
    public bool Remove(TKey key)
    {
        return this.realDictionary.Remove(key);
    }

    /// <summary>
    /// Gets the value associated with the specified key.
    /// </summary>
    /// <param name="key">The key whose value to get.</param>
    /// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized.</param>
    /// <returns>
    /// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key; otherwise, false.
    /// </returns>
    /// <exception cref="T:System.ArgumentNullException">
    /// <paramref name="key"/> is null.
    /// </exception>
    public bool TryGetValue(TKey key, out TValue value)
    {
        WeakReference<TValue> reference;
        if (this.realDictionary.TryGetValue(key, out reference))
        {
            value = reference.Target;
            return true;
        }
        else
        {
            value = default(TValue);
            return false;
        }
    }

    /// <summary>
    /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
    /// </summary>
    /// <value></value>
    /// <returns>
    /// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
    /// </returns>
    public ICollection<TValue> Values
    {
        get
        {
            return this.realDictionary
                .Values
                .Select(value => value.Target)
                .ToList()
                .AsReadOnly();
        }
    }

    /// <summary>
    /// Gets or sets the value associated with the specified key.
    /// </summary>
    /// <param name="key">The key of the value to get or set.</param>
    /// <returns>The value associated with the specified key. If the specified key is not
    /// found, a get operation throws a <see cref="System.Collections.Generic.KeyNotFoundException"/>,
    /// and a set operation creates a new element with the specified key.</returns>
    /// <exception cref="System.ArgumentNullException">
    /// <paramref name="key"/> is <c>null</c>.
    /// </exception>
    /// <exception cref="System.Collections.Generic.KeyNotFoundException">
    /// The property is retrieved and the key does not exist in the collection.
    /// </exception>
    public TValue this[TKey key]
    {
        get
        {
            return this.realDictionary[key].Target;
        }
        set
        {
            this.realDictionary[key] = new WeakReference<TValue>(value);
        }
    }

    #endregion

    #region ICollection<KeyValuePair<TKey,TValue>> Members

    /// <summary>
    /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
    /// </summary>
    /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
    /// <exception cref="T:System.NotSupportedException">
    /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
    /// </exception>
    void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
    {
        Add(item.Key, item.Value);
    }

    /// <summary>
    /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
    /// </summary>
    /// <exception cref="T:System.NotSupportedException">
    /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
    /// </exception>
    public void Clear()
    {
        this.realDictionary.Clear();
    }

    /// <summary>
    /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
    /// </summary>
    /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
    /// <returns>
    /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
    /// </returns>
    bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
    {
        return this.realDictionary.ContainsKey(item.Key);
    }

    /// <summary>
    /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
    /// </summary>
    /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
    /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
    /// <exception cref="T:System.ArgumentNullException">
    /// 	<paramref name="array"/> is null.
    /// </exception>
    /// <exception cref="T:System.ArgumentOutOfRangeException">
    /// 	<paramref name="arrayIndex"/> is less than 0.
    /// </exception>
    /// <exception cref="T:System.ArgumentException">
    /// 	<paramref name="array"/> is multidimensional.
    /// -or-
    /// <paramref name="arrayIndex"/> is equal to or greater than the length of <paramref name="array"/>.
    /// -or-
    /// The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.
    /// -or-
    /// Type <paramref name="T"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.
    /// </exception>
    void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
    {
        if (array == null)
        {
            throw new ArgumentNullException("array", "Array cannot be null");
        }

        if ( (arrayIndex < 0) || (arrayIndex > array.Length) )
        {
            throw new ArgumentOutOfRangeException("array", "Index must be a non-negative value within the array");
        }

        if ((array.Length - arrayIndex) < this.realDictionary.Count)
        {
            throw new ArgumentException("Array is too small", "array");
        }

        foreach (var pair in this.realDictionary)
        {
            array[arrayIndex++] = new KeyValuePair<TKey, TValue>(pair.Key, pair.Value.Target);
        }
    }

    /// <summary>
    /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
    /// </summary>
    /// <value></value>
    /// <returns>
    /// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
    /// </returns>
    public int Count
    {
        get
        {
            return this.realDictionary.Count;
        }
    }

    /// <summary>
    /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
    /// </summary>
    /// <value></value>
    /// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
    /// </returns>
    public bool IsReadOnly
    {
        get
        {
            return false;
        }
    }

    /// <summary>
    /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
    /// </summary>
    /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
    /// <returns>
    /// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
    /// </returns>
    /// <exception cref="T:System.NotSupportedException">
    /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
    /// </exception>
    bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
    {
        return Remove(item.Key);
    }

    #endregion

    #region IEnumerable<KeyValuePair<TKey,TValue>> Members

    /// <summary>
    /// Returns an enumerator that iterates through the collection.
    /// </summary>
    /// <returns>
    /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
    /// </returns>
    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
    {
        foreach (var pair in this.realDictionary)
        {
            yield return new KeyValuePair<TKey, TValue>(pair.Key, pair.Value.Target);
        }
    }

    #endregion

    #region IEnumerable Members

    /// <summary>
    /// Returns an enumerator that iterates through a collection.
    /// </summary>
    /// <returns>
    /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
    /// </returns>
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    #endregion
}

So there you have it, WeakReferenceDictionary<TKey, TValue>. It's not a complete replacement for a regular dictionary as it doesn't support all the same interfaces such as the ICollection or ISerialization. Also, I haven't fully commented everything as well as perhaps it should be. I'll leave all that as an exercise for you.

Strongly-typed WeakReference

I was playing around with weak references recently and wanted to tidy up my code a little – there were casts everywhere – so I knocked up a derivation using generics. I'm sure someone somewhere already did this, but I thought I'd share it anyway, so here it is.

/// <summary>
/// Strongly-typed weak reference.
/// </summary>
/// <typeparam name="T">The type of object being referenced.</typeparam>
public class WeakReference<T> : WeakReference, ISerializable where T : class
{
    /// <summary>
    /// Initializes a new instance of the  <see cref="WeakReference<T>"/> class, referencing
    /// the specified object.
    /// </summary>
    /// <param name="target">An object to track.</param>
    public WeakReference(T target)
        : base(target)
    {

    }

    /// <summary>
    /// Initializes a new instance of the  <see cref="WeakReference<T>"/> class, referencing
    /// the specified object and using the specified resurrection tracking.
    /// </summary>
    /// <param name="target">An object to track.</param>
    /// <param name="trackResurrection">Indicates when to stop tracking the object. If <c>true</c>, the object is tracked
    /// after finalization; if <c>false</c>, the object is only tracked until finalization..</param>
    public WeakReference(T target, bool trackResurrection)
        : base(target, trackResurrection)
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="WeakReference<T>"/> class.
    /// </summary>
    /// <param name="info">An object that holds all the data needed to serialize or deserialize the current <see cref="T:System.WeakReference"/> object.</param>
    /// <param name="context">(Reserved) Describes the source and destination of the serialized stream specified by <paramref name="info"/>.</param>
    /// <exception cref="T:System.ArgumentNullException">
    /// 	<paramref name="info"/> is null. </exception>
    protected WeakReference(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
    }

    /// <summary>
    /// Gets or sets the object (the target) referenced by the current <see cref="T:System.WeakReference"/> object.
    /// </summary>
    /// <value></value>
    /// <returns>null if the object referenced by the current <see cref="T:System.WeakReference"/> object has been garbage collected; otherwise, a reference to the object referenced by the current <see cref="T:System.WeakReference"/> object.</returns>
    /// <exception cref="T:System.InvalidOperationException">The reference to the target object is invalid. This exception can be thrown while setting this property if the value is a null reference or if the object has been finalized during the set operation.</exception>
    public new T Target
    {
        get
        {
            return (T)base.Target;
        }

        set
        {
            base.Target = value;
        }
    }
}

There's not much to say about this class. I've replaced the Target property of the original WeakReference class with a strongly-typed one based on the type parameter, T. The other bits are just constructors to mirror those in the base class and it's job done.