C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: The program uses the fixed statement to ensure that the garbage collector does not relocate the string data.
Fixed: Inside the fixed statement is a block of code. The string data pointed to by the char* pointer will not be moved.
And: This means we can manipulate that memory however we like. In the example, we increment the value of each character.
Loop: The program adds 1 to each character in the string. It does this through pointer manipulation.
C# program that uses fixed statement on string
using System;
class Program
{
static void Main()
{
Console.WriteLine(Transform());
Console.WriteLine(Transform());
Console.WriteLine(Transform());
}
unsafe static string Transform()
{
// Get random string.
string value = System.IO.Path.GetRandomFileName();
// Use fixed statement on a char pointer.
// ... The pointer now points to memory that won't be moved.
fixed (char* pointer = value)
{
// Add one to each of the characters.
for (int i = 0; pointer[i] != '\0'; ++i)
{
pointer[i]++;
}
// Return the mutated string.
return new string(pointer);
}
}
}
Output
61c4eu6h/zt1
ctqqu62e/r2v
gbekvhn6/xwq
Size: The size of the fixed buffer must be constant—you can use a constant expression.
Note: The program uses a static struct reference containing a fixed buffer of integers.
Load, Store: In Load and Store(), the program reads and writes values to the fixed buffer using unsafe code and pointers.
StaticC# program that uses fixed buffer and unsafe context
using System;
unsafe struct FixedBufferExample
{
public fixed int _buffer[1024]; // This is a fixed buffer.
}
class Program
{
static FixedBufferExample _fixedBufferExample; // Reference to struct.
static void Main()
{
// Store values in the fixed buffer.
// ... The load the values from the fixed buffer.
Store();
Load();
}
unsafe static void Store()
{
// Put the fixed buffer in unmovable memory.
// ... Then assign some elements.
fixed (int* buffer = _fixedBufferExample._buffer)
{
buffer[0] = 1;
buffer[99] = 2;
buffer[1023] = 3;
}
}
unsafe static void Load()
{
// Put in unmovable memory.
// ... Then load some values from the memory.
fixed (int* buffer = _fixedBufferExample._buffer)
{
Console.WriteLine(buffer[0]);
Console.WriteLine(buffer[99]);
Console.WriteLine(buffer[1023]);
}
}
}
Output
1
2
3
Info: A fixed buffer could be faster on long-running computations that are heavily numerical.
Tip: As always, when improving performance, please set up benchmarks and only accept changes that result in an improvement.
BenchmarkThus: If you are optimizing, make sure to benchmark all the unsafe changes you make.
Info: Thanks to Amit Jha for pointing out that fixed statements can lead to performance improvements in certain situations.