Interlocked::Exchange<T> Method (T%, T)
Sets a variable of the specified type T to a specified value and returns the original value, as an atomic operation.
Assembly: mscorlib (in mscorlib.dll)
public: generic<typename T> where T : ref class [ComVisibleAttribute(false)] static T Exchange( T% location1, T value )
Parameters
- location1
-
Type:
T%
The variable to set to the specified value. This is a reference parameter (ref in C#, ByRef in Visual Basic).
- value
-
Type:
T
The value to which the location1 parameter is set.
Return Value
Type: TThe original value of location1.
Type Parameters
- T
The type to be used for location1 and value. This type must be a reference type.
| Exception | Condition |
|---|---|
| NullReferenceException | The address of location1 is a null pointer. |
This method only supports reference types. There are overloads of the Exchange method for the Int32, Int64, IntPtr, Single, and Double value types, but there is no support for other value types.
Note |
|---|
This method overload is preferable to the Exchange(Object^%, Object^) method overload, because the latter requires late-bound access to the destination object . |
Available since 8
.NET Framework
Available since 2.0
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1

The example uses the firstWidget variable to store the ID that occurs first in the sort order. It compares each ID that it generates with the firstWidget value. If the new value precedes the current value of firstWidget in the sort order, the example calls the Exchange<T> method to assign the new value to firstWidget.