References the specified object, which makes it ineligible for garbage collection from the start of the current routine to the point where this method is called.
Assembly: mscorlib (in mscorlib.dll)
The purpose of the method is to ensure the existence of a reference to an object that is at risk of being prematurely reclaimed by the garbage collector. A common scenario where this might happen is when there are no references to the object in managed code or data, but the object is still in use in unmanaged code such as Win32 APIs, unmanaged DLLs, or methods using COM.
This method references the obj parameter, making that object ineligible for garbage collection from the start of the routine to the point, in execution order, where this method is called. Code this method at the end, not the beginning, of the range of instructions where obj must be available.
The method performs no operation and produces no side effects other than extending the lifetime of the object passed in as a parameter.
The following code example creates an object at the beginning of its Main method and does not refer to the object again until the end, when the method is called. The object persists for the 30-second duration of the Main method, despite calls to the Collect and WaitForPendingFinalizers methods.
.NET FrameworkSupported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1
.NET Framework Client ProfileSupported in: 4, 3.5 SP1
XNA FrameworkSupported in: 3.0, 2.0, 1.0
Portable Class LibrarySupported in: Portable Class Library
Supported in: Windows Phone 8.1
Supported in: Windows Phone Silverlight 8.1
Supported in: Windows Phone Silverlight 8