ConditionalWeakTable<TKey,TValue> ConditionalWeakTable<TKey,TValue> ConditionalWeakTable<TKey,TValue> ConditionalWeakTable<TKey,TValue> Class

Definition

Enables compilers to dynamically attach object fields to managed objects.

generic <typename TKey, typename TValue>
 where TKey : class where TValue : classpublic ref class ConditionalWeakTable sealed
[System.Runtime.InteropServices.ComVisible(false)]
public sealed class ConditionalWeakTable<TKey,TValue> where TKey : class where TValue : class
type ConditionalWeakTable<'Key, 'Value (requires 'Key : null and 'Value : null)> = class
Public NotInheritable Class ConditionalWeakTable(Of TKey, TValue)

Type Parameters

TKey

The reference type to which the field is attached.

TValue

The field's type. This must be a reference type.

Inheritance
ConditionalWeakTable<TKey,TValue>ConditionalWeakTable<TKey,TValue>ConditionalWeakTable<TKey,TValue>ConditionalWeakTable<TKey,TValue>
Attributes

Examples

The following example illustrates that a key stored in the ConditionalWeakTable<TKey,TValue> table does not persist after references to it outside the table are destroyed. The example defines two classes: ManagedClass, which represents the key in the table, and ClassData, which represents the key's value. The example instantiates three objects of each type. It also instantiates a WeakReference object that represents the second ManagedClass, and then destroys the second ManagedClass instance. The attempt to retrieve the second ManagedClass object from the Target property indicates that no references to the object remain.

using System;
using System.Runtime.CompilerServices;

public class Example
{
   public static void Main()
   {
      var mc1 = new ManagedClass();
      var mc2 = new ManagedClass();
      var mc3 = new ManagedClass();
      
      var cwt = new ConditionalWeakTable<ManagedClass, ClassData>();
      cwt.Add(mc1, new ClassData());          
      cwt.Add(mc2, new ClassData());
      cwt.Add(mc3, new ClassData());
      
      var wr2 = new WeakReference(mc2);
      mc2 = null;

      GC.Collect();
      
      ClassData data = null; 

      if (wr2.Target == null)
          Console.WriteLine("No strong reference to mc2 exists.");   
      else if (cwt.TryGetValue(mc2, out data))
          Console.WriteLine("Data created at {0}", data.CreationTime);      
      else
          Console.WriteLine("mc2 not found in the table.");
   }
}

public class ManagedClass
{ 
}

public class ClassData
{
   public DateTime CreationTime;
   public object Data;   
   
   public ClassData()
   {
      CreationTime = DateTime.Now;
      this.Data  = new object();     
   }
}
// The example displays the following output:
//       No strong reference to mc2 exists.
Imports System.Runtime.CompilerServices

Module Example
   Public Sub Main()
      Dim mc1 As New ManagedClass()
      Dim mc2 As New ManagedClass()
      Dim mc3 As New ManagedClass()
                    
      Dim cwt As New ConditionalWeakTable(Of ManagedClass, ClassData)()
      cwt.Add(mc1, New ClassData())          
      cwt.Add(mc2, New ClassData())
      cwt.Add(mc3, New ClassData())
      
      Dim wr2 As New WeakReference(mc2)
      mc2 = Nothing

      GC.Collect()

      Dim data As ClassData = Nothing

      If wr2.Target Is Nothing Then
          Console.WriteLine("No strong reference to mc2 exists.")   
      Else If cwt.TryGetValue(mc2, data) Then
          Console.WriteLine("Data created at {0}", data.CreationTime)      
      Else
          Console.WriteLine("mc2 not found in the table.")
      End If
   End Sub
End Module

Public Class ManagedClass
End Class

Public Class ClassData
   Public CreationTime As DateTime
   Public Data As Object   
   
   Public Sub New()
      Me.CreationTime = DateTime.Now
      Me.Data  = New Object()     
   End Sub
End Class
' The example displays the following output:
'       No strong reference to mc2 exists.

Remarks

The ConditionalWeakTable<TKey,TValue> class enables language compilers to attach arbitrary properties to managed objects at run time. A ConditionalWeakTable<TKey,TValue> object is a dictionary that binds a managed object, which is represented by a key, to its attached property, which is represented by a value. The object's keys are the individual instances of the TKey class to which the property is attached, and its values are the property values that are assigned to the corresponding objects.

Keys must be unique; in other words, the ConditionalWeakTable<TKey,TValue> class supports one attached value per managed object. Two keys are equal if passing them to the Object.ReferenceEquals method returns true.

Note

You cannot control equality comparisons by overriding Object.GetHashCode to explicitly set the hash code for a key. The ConditionalWeakTable<TKey,TValue> class does not use the Object.GetHashCode method to compute hash codes, and therefore does not invoke Object.GetHashCode overrides.

Although the ConditionalWeakTable<TKey,TValue> class holds a collection of key/value pairs, it is best thought of as a table rather than a dictionary object. The ConditionalWeakTable<TKey,TValue> class differs from a dictionary in several ways:

  • It does not persist keys. That is, a key is not kept alive only because it is a member of the collection.

  • It does not include all the methods (such as GetEnumerator or Contains) that a dictionary typically has.

  • It does not implement the IDictionary<TKey,TValue> interface.

The ConditionalWeakTable<TKey,TValue> class differs from other collection objects in its management of the object lifetime of keys stored in the collection. Ordinarily, when an object is stored in a collection, its lifetime lasts until it is removed (and there are no additional references to the object) or until the collection object itself is destroyed. However, in the ConditionalWeakTable<TKey,TValue> class, adding a key/value pair to the table does not ensure that the key will persist, even if it can be reached directly from a value stored in the table (for example, if the table contains one key, A, with a value V1, and a second key, B, with a value P2 that contains a reference to A). Instead, ConditionalWeakTable<TKey,TValue> automatically removes the key/value entry as soon as no other references to a key exist outside the table. The example provides an illustration.

Constructors

ConditionalWeakTable<TKey,TValue>() ConditionalWeakTable<TKey,TValue>() ConditionalWeakTable<TKey,TValue>() ConditionalWeakTable<TKey,TValue>()

Initializes a new instance of the ConditionalWeakTable<TKey,TValue> class.

Methods

Add(TKey, TValue) Add(TKey, TValue) Add(TKey, TValue) Add(TKey, TValue)

Adds a key to the table.

AddOrUpdate(TKey, TValue) AddOrUpdate(TKey, TValue) AddOrUpdate(TKey, TValue) AddOrUpdate(TKey, TValue)
Clear() Clear() Clear() Clear()
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()

Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the ConditionalWeakTable<TKey,TValue> object.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetOrCreateValue(TKey) GetOrCreateValue(TKey) GetOrCreateValue(TKey) GetOrCreateValue(TKey)

Atomically searches for a specified key in the table and returns the corresponding value. If the key does not exist in the table, the method invokes the default constructor of the class that represents the table's value to create a value that is bound to the specified key.

GetType() GetType() GetType() GetType()

Gets the Type of the current instance.

(Inherited from Object)
GetValue(TKey, ConditionalWeakTable<TKey,TValue>) GetValue(TKey, ConditionalWeakTable<TKey,TValue>) GetValue(TKey, ConditionalWeakTable<TKey,TValue>) GetValue(TKey, ConditionalWeakTable<TKey,TValue>)

Atomically searches for a specified key in the table and returns the corresponding value. If the key does not exist in the table, the method invokes a callback method to create a value that is bound to the specified key.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
Remove(TKey) Remove(TKey) Remove(TKey) Remove(TKey)

Removes a key and its value from the table.

ToString() ToString() ToString() ToString()

Returns a string that represents the current object.

(Inherited from Object)
TryGetValue(TKey, TValue) TryGetValue(TKey, TValue) TryGetValue(TKey, TValue) TryGetValue(TKey, TValue)

Gets the value of the specified key.

Explicit Interface Implementations

IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()
IEnumerable<KeyValuePair<TKey,TValue>>.GetEnumerator() IEnumerable<KeyValuePair<TKey,TValue>>.GetEnumerator() IEnumerable<KeyValuePair<TKey,TValue>>.GetEnumerator() IEnumerable<KeyValuePair<TKey,TValue>>.GetEnumerator()

Applies to

Thread Safety

Instances of the ConditionalWeakTable<TKey,TValue> class are thread safe. They do not require callers to do any additional locking.