Take advantage of the unsafe keyword to write unmanaged code in .Net The C# programming language doesn’t allow you to work with pointers by default. You need to use the unsafe keyword to define an unsafe context and write code that uses pointers. Unsafe code helps you write unmanaged code that wouldn’t be handled by the execution environment of the CLR. This article takes a look at how we can work with unsafe code in the managed environment of .Net. What is unsafe code anyway? With unsafe code, the safety of the code cannot be verified by the CLR. In other words, unsafe or unmanaged code is executed outside of the context of the CLR. Unsafe code helps you invoke native functions using pointers. Note that when writing unsafe code you should ensure the program doesn’t incur any security risks, memory faults, or so on. To write unsafe code, you should use the unsafe keyword. You define methods, types, and code blocks as unsafe using the unsafe keyword. Pointers A pointer is a variable that points to the address of another variable. In other words, a pointer holds the memory address of another variable or a memory location. Note that the data type of a pointer should match the data type of the variable to which it points. Hence, for a pointer to indicate an integer variable, the type of the pointer should be integer. The three operators that you would frequently make use of while working with pointers include the following: * & -> The following piece of code shows how you can define a pointer and make it point to the address of a variable. int i = 100; int *ptr = & i; Refer to the code snippet above. In the first statement we assign the value 100 to an integer variable. In the next statement we define an integer pointer and make it point to the address of the variable using the & operator. Here’s a snippet of code that illustrates how we can use the unsafe keyword to display the memory address of a variable. static void Main(string[] args) { unsafe { int i = 100; int* ptr = &i; Console.WriteLine ("The value of i is : " + i); Console.WriteLine ("The memory address of i is : " + (int)ptr); } Console.ReadKey(); } Note that usage of the unsafe keyword. If you omit unsafe and compile the above code, you would see the following error. “Pointers may only be used in an unsafe context”. The above error message clearly states that you should write your unsafe code within an unsafe context — exactly what unsafe provides you. Assuming you’re using Visual Studio IDE for writing and compiling your program(s) that leverage unsafe code, you should enable unsafe code for your project in the Visual Studio IDE. To do so, follow these steps: Select the project and right-click on it In the project properties window, click on the Build tab Next, select the “Allow unsafe code” check box Note that you can also compile your program that contains unsafe code using the csc command-line compiler as shown below: csc /unsafe myprogram.cs The above program when executed would display the value and also the memory address of the variable i. You can also mark a method as unsafe via the unsafe keyword. Here’s an example that shows how you can do this: public unsafe void Compute(int* ptr) { *ptr = (*ptr) * 10; } You can now invoke the Compute function as shown below. unsafe { int i = 100; int* ptr = &i; Compute(&i); Console.WriteLine("The value of the variable i is : " + i); } When you execute the above code snippet, you would observe that the value of the variable i has been changed from 100 (its initial value) to 1,000. The Compute function accepts a pointer as an argument and multiplies the value of the variable to which the pointer points by 10. Note that *ptr refers to the content of the variable to which ptr points, which incidentally is 100. This value is multiplied by 10 — hence the result. When working with unsafe code in a managed environment you might need to use the fixed keyword to logically place the variable in memory so that the runtime doesn’t move the variable around in memory while compacting the memory due to heap fragmentation. In essence, you can use the fixed keyword to eliminate the issues related to invalid pointers. You can also use fixed to pin an array and retrieve pointer to the data in the array. I would discuss more on unmanaged code in my future articles here. Related content feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos