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 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos