Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to compile unsafe code in C#?
Unsafe code in C# allows direct memory manipulation using pointers, which bypasses the .NET garbage collector's safety mechanisms. To compile unsafe code, you need to enable unsafe context compilation through specific compiler settings.
Command-Line Compilation
For compiling unsafe code using the command-line compiler, you must specify the /unsafe switch −
csc /unsafe filename.cs
For example, to compile a program named one.cs containing unsafe code −
csc /unsafe one.cs
Visual Studio IDE Configuration
In Visual Studio, you need to enable unsafe code compilation in the project properties. Follow these steps −
- Open Project Properties by right-clicking the project in Solution Explorer and selecting "Properties"
- Click on the "Build" tab
- Check the option "Allow unsafe code"
- Save and rebuild your project
Modern .NET Project Files
For modern .NET projects using SDK-style project files, you can enable unsafe code by adding the following property to your .csproj file −
<PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup>
Example of Unsafe Code Compilation
Here's a simple example showing how unsafe code works once compilation is enabled −
using System;
class Program {
static unsafe void Main() {
int number = 42;
int* ptr = &number;
Console.WriteLine("Value: " + number);
Console.WriteLine("Address: " + (long)ptr);
Console.WriteLine("Value via pointer: " + *ptr);
*ptr = 100;
Console.WriteLine("New value: " + number);
}
}
The output of the above code is −
Value: 42 Address: 140734516744220 Value via pointer: 42 New value: 100
Conclusion
Compiling unsafe code in C# requires enabling unsafe context through the /unsafe compiler switch, Visual Studio project settings, or the AllowUnsafeBlocks property in modern .NET projects. Once enabled, you can use pointers and direct memory manipulation within unsafe blocks or methods.
