Open In App
Related Articles

Unsafe Code in C#

Improve Article
Save Article
Like Article

Unsafe code in C# is the part of the program that runs outside the control of the Common Language Runtime (CLR) of the .NET frameworks. The CLR is responsible for all of the background tasks that the programmer doesn’t have to worry about like memory allocation and release, managing stack etc. Using the keyword “unsafe” means telling the compiler that the management of this code will be done by the programmer. Making a code content unsafe introduces stability and security risks as there are no bound checks in cases of arrays, memory related errors can occur which might remain unchecked etc.

A programmer can make the following sub-programs as unsafe:

  1. Code blocks
  2. Methods
  3. Types
  4. Class
  5. Struct

Need to use the unsafe code?

  • When the program needs to implement pointers.
  • If native methods are used.


unsafe Context_declaration

Example: Here, we are declaring a block of code inside main as unsafe so that we can use pointers.

// C# program to demonstrate the unsafe code
using System;
namespace GFG {
class Program {
    // Main Method
    static void Main(string[] args)
        // Declaring a code block as 
        // unsafe to make use of pointers
            int x = 10;
            int* ptr;
            ptr = &x;
            // displaying value of x using pointer
            Console.WriteLine("Inside the unsafe code block");
            Console.WriteLine("The value of x is " + *ptr);
        } // end unsafe block
        Console.WriteLine("\nOutside the unsafe code block");
    } // end main

Note: This code will not compile directly, it gives the following error.

Therefore, if you are using Visual Studio, then you need to follow the given steps:

1) Go to the project properties

2) Select the build option and check the “Allow unsafe code” option.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 11 Mar, 2019
Like Article
Save Article
Similar Reads