What's the use of C# keyword fixed/unsafe?

c#

Solution

C# is a managed language that means the memory is managed automatically, i.e. not by you. If you did not use `fixed` by the time you come to modify the memory pointed to by your pointer C# could have moved the variable to another memory location so you could be modifying something else!

`fixed` is logically fixing the variable in memory so it does not move around.

Why does C# move variables in memory around? To compact the memory otherwise programs would use up more memory available to them if objects that are no longer alive left holes other objects cannot fit in (heap memory fragmentation).

I used `fixed` extensively in a .NET library designed for resource constrained devices to avoid creating garbage copying into buffers and find this feature sorely lacking in other managed languages where you cannot do the same. When writing games in a managed language garbage collection is often one of the biggest bottlenecks so having the ability not to create it is very helpful!

See my question here: C# Copy variables into buffer without creating garbage? for one reason why.

Problem

What's the use of C# keyword fixed/unsafe? For example, C# fixed Keyword (unsafe) ``` using System; class Program { unsafe static void Main() { fixed (char* value = "sam") { char* ptr = value; while (*ptr != '\0') { Console.WriteLine(*ptr); ++ptr; } } } } ``` Why do I need to fix it in the first place?

Original source

Related problems