C# Keywords Tutorial Part 33: fixed
Amr Saafan
Founder | CTO | Software Architect & Consultant | Engineering Manager | Project Manager | Product Owner | +27K Followers | Now Hiring!
C# is a programming language that packs a punch with its rich features, and one such feature is the “fixed” keyword. Developers use the “fixed” keyword to define a pointer variable that points to a specific memory location that cannot be changed. In this blog post, we will delve into the intricacies of the “fixed” keyword and present examples to help you grasp its functioning.
The “fixed” keyword in C# comes in handy when declaring a buffer of fixed size. Once a buffer is declared as fixed, it means that the buffer’s size is known at compile time, and the memory for the buffer is allocated on the stack instead of the heap. This aids in improving performance by reducing the time it takes to allocate and deallocate memory.
Here is an example of how to use the “fixed” keyword to declare a fixed-size buffer:
unsafe
{
? ? int[] array = new int[10];
? ? fixed(int* p = array)
? ? {
? ? ? ? // Use the pointer here
? ? }
}
In this example, we declare an integer array with 10 elements and then use the “fixed” keyword to declare a pointer variable “p” that points to the first element of the array. The “unsafe” keyword is used to indicate that we are using unsafe code, which requires elevated permissions to run.
Once we have declared the pointer variable, we can use it to access the elements of the array. Here is an example of how to use the pointer to set the first element of the array to 42:
unsafe
{
? ? int[] array = new int[10];
? ? fixed(int* p = array)
? ? {
? ? ? ? *p = 42;
? ? }
}
In this example, we use the pointer “p” to access the first element of the array by dereferencing the pointer with the * operator. We then assign the value 42 to the first element of the array.
领英推荐
The “fixed” keyword can also be used to declare a fixed-size buffer of a struct. Here is an example:
unsafe struct MyStruct
{
? ? public int Value1;
? ? public int Value2;
}
unsafe
{
? ? MyStruct myStruct;
? ? fixed(MyStruct* p = &myStruct)
? ? {
? ? ? ? // Use the pointer here
? ? }
}
In this example, we declare a struct “MyStruct” with two integer fields. We then use the “fixed” keyword to declare a pointer variable “p” that points to the memory location of the struct. The & operator is used to get the address of the struct.
Once we have declared the pointer variable, we can use it to access the fields of the struct. Here is an example of how to use the pointer to set the values of the struct fields:
unsafe
{
? ? MyStruct myStruct;
? ? fixed(MyStruct* p = &myStruct)
? ? {
? ? ? ? p->Value1 = 42;
? ? ? ? p->Value2 = 24;
? ? }
}
In this example, we use the pointer “p” to access the fields of the struct by using the -> operator. We then assign the values 42 and 24 to the Value1 and Value2 fields of the struct.