Interlocked.CompareExchange Method (Object%, Object, Object)

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Compares two objects for reference equality and, if they are equal, replaces one of the objects.

Namespace:  System.Threading
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
<SecuritySafeCriticalAttribute> _
Public Shared Function CompareExchange ( _
    ByRef location1 As Object, _
    value As Object, _
    comparand As Object _
) As Object
[SecuritySafeCriticalAttribute]
public static Object CompareExchange(
    ref Object location1,
    Object value,
    Object comparand
)

Parameters

  • location1
    Type: System.Object%
    The destination object that is compared with comparand and possibly replaced.
  • value
    Type: System.Object
    The object that replaces the destination object if the comparison results in equality.
  • comparand
    Type: System.Object
    The object that is compared to the object at location1.

Return Value

Type: System.Object
The original value in location1.

Exceptions

Exception Condition
ArgumentNullException

The address of location1 is a null pointer.

Remarks

If comparand and the object in location1 are equal, then value is stored in location1. Otherwise, no operation is performed. The compare and exchange operations are performed as an atomic operation. The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.

Beginning with .NET Framework version 2.0, the CompareExchange<T>(T%, T, T) method overload provides a type-safe alternative for reference types.

NoteNote:

The objects are compared for reference equality, rather than Object.Equals. As a result, two boxed instances of the same value type (for example, the integer 3) always appear to be unequal, and no operation is performed. Do not use this overload with value types.

Version Information

Silverlight

Supported in: 5, 4

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.