Skip to content

Latest commit

 

History

History
57 lines (43 loc) · 3.19 KB

File metadata and controls

57 lines (43 loc) · 3.19 KB
title fixed Statement (C# Reference)
ms.date 07/20/2015
ms.prod .net
ms.technology
devlang-csharp
ms.topic article
f1_keywords
fixed_CSharpKeyword
fixed
helpviewer_keywords
fixed keyword [C#]
ms.assetid 7ea6db08-ad49-4a7a-b934-d8c4acad1c3a
caps.latest.revision 24
author BillWagner
ms.author wiwagn

fixed Statement (C# Reference)

The fixed statement prevents the garbage collector from relocating a movable variable. The fixed statement is only permitted in an unsafe context. Fixed can also be used to create fixed size buffers.

The fixed statement sets a pointer to a managed variable and "pins" that variable during the execution of the statement. Without fixed, pointers to movable managed variables would be of little use since garbage collection could relocate the variables unpredictably. The C# compiler only lets you assign a pointer to a managed variable in a fixed statement.

[!code-csharpcsrefKeywordsFixedLock#1]

You can initialize a pointer by using an array, a string, a fixed-size buffer, or the address of a variable. The following example illustrates the use of variable addresses, arrays, and strings. For more information about fixed-size buffers, see Fixed Size Buffers.

[!code-csharpcsrefKeywordsFixedLock#2]

You can initialize multiple pointers, as long as they are all of the same type.

fixed (byte* ps = srcarray, pd = dstarray) {...}  

To initialize pointers of different types, simply nest fixed statements, as shown in the following example.

[!code-csharpcsrefKeywordsFixedLock#3]

After the code in the statement is executed, any pinned variables are unpinned and subject to garbage collection. Therefore, do not point to those variables outside the fixed statement.

Note

Pointers initialized in fixed statements cannot be modified.

In unsafe mode, you can allocate memory on the stack, where it is not subject to garbage collection and therefore does not need to be pinned. For more information, see stackalloc.

Example

[!code-csharpcsrefKeywordsFixedLock#4]

C# Language Specification

[!INCLUDECSharplangspec]

See Also

C# Reference
C# Programming Guide
C# Keywords
unsafe
Fixed Size Buffers