C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: The "\0" character is used by the .NET Framework to terminate a string. We need to know this only for unsafe code.
CharStringsC# program that uses unsafe code
using System;
class Program
{
unsafe static void Main()
{
fixed (char* value = "sam")
{
char* ptr = value;
while (*ptr != '\0')
{
Console.WriteLine(*ptr);
++ptr;
}
}
}
}
Output
s
a
m
Note: If you try to compile these programs, you will get this error: "Unsafe code may only appear if compiling with /unsafe".
And: To solve this in Visual Studio, go to Project > Properties > Build and check "Allow unsafe code".
C# program that uses unsafe block
using System;
class Program
{
static void Main()
{
unsafe
{
fixed (char* value = "sam")
{
char* ptr = value;
while (*ptr != '\0')
{
Console.WriteLine(*ptr);
++ptr;
}
}
}
}
}
Output
s
a
m
And: We use the fixed statement to create an unmovable memory block. This allows pointer access.
FixedCaution: Stackalloc is not usually a good optimization in managed code. It introduces some overhead.
stackallocHowever: This applies unless you know exactly what you are doing and are willing to put a lot of effort into your solution.
Quote: Interfacing with the operating system, accessing a memory-mapped device, or implementing a time-critical algorithm may not be possible or practical without access to pointers (The C# Programming Language).
Quote: A pointer type is a compile-time description of a value whose representation is a machine address of a location (The CLI Annotated Standard).