C# - Unsafe Code Using Pointers Example

Here, we will learn how to compile unsafe code in C#?
Submitted by Nidhi, on November 01, 2020 [Last updated : March 23, 2023]

How to Compile Unsafe Code?

To compile unsafe code we need to allow unsafe code by clicking on properties in solution explorer and then "Allow Unsafe Code" from the Build tab.

C# program to demonstrate the example of unsafe code using pointers

The source code to demonstrate the unsafe code using pointers is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# - Unsafe Code Using Pointers Example.

using System;

class UnsafeEx
{
    static unsafe void Main(string[] args)
    {
        int num = 10;
        int* ptr;
        
        ptr= #
        
        Console.WriteLine("Value  : " + *ptr);
        Console.WriteLine("Address: " + (int)ptr);
    }
}

Output

Value  : 10
Address: 3207180
Press any key to continue . . .

Explanation

In the above program, we created class UnsafeEx that contains the Main() method, here we used the unsafe keyword with the Main() method to define the unsafe method that can use pointers.

In the Main() method, we created a variable num, which is initialized with 10. Here, we also created an integer pointer then assign the address of the num variable into pointer ptr, and then print value and address using the pointer.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.