Interlocked.CompareExchange Method (Object, Object, Object)

Compares two objects for reference equality and, if they are equal, replaces the first object.

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

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.

ExceptionCondition
ArgumentNullException

The address of location1 is a null pointer.

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.

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft