C# Unsafe Keyword Guide

In C#, using the unsafe keyword allows for the use of unsafe pointer operations in the code. Here is a simple example demonstrating how to use the unsafe keyword in C#:

using System;

class Program
{
    static unsafe void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };

        fixed (int* p = numbers)
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(*(p + i));
            }
        }
    }
}

In this example, we declared the Main method using the unsafe keyword and used a fixed statement in the method body to create a pointer p to an array of integers called numbers. We then used the pointer p to access elements in the array and printed out their values.

It is important to note that when using the “unsafe” keyword, you need to enable the “Allow unsafe code” option in the project properties. This can be done by setting it to True in Visual Studio under Project Properties -> Build -> Allow unsafe code.

bannerAds