How to Work with Unsafe Code in C#

C# Programming Guide

C# is a powerful programming language that is used to create applications for Windows, Android, and many other platforms. It also has a robust type system, which makes it easy to write safe code. However, sometimes you need to work with unsafe code – code that might not adhere to the safety rules of the CLR.

The CLR cannot verify the source code’s safety when using unsafe code. The reason is that unmanaged or unsafe code is executed outside of the CLR environment. Unsafe code allows you to call native functions using pointers.

It should be noted that while developing unsafe code, you should ensure that the application does not introduce any security vulnerabilities, memory problems, or other issues.

Want to learn C# and .NET in a course or class environment? Check out our list of the Best Online Courses to Learn .NET.

What Is Unsafe Code?

Unsafe code refers to source code that is not verified by the CLR. In C#, unsafe code is implemented using the unsafe keyword. You can use the unsafe keyword mark code blocks, types, and methods as unsafe. However, when writing unsafe code, it is important to keep in mind the potential security implications.

If you are using the unsafe keyword in Visual Studio, you must enable “Allow unsafe code”/b>. To do this, you can switch to the Build tab in the Project properties dialog box and then check this option in the checkbox.

Here are a few tips for working with unsafe code in C#:

  • Unsafe code can lead to security vulnerabilities, so be sure to use it only when necessary.
  • Always make sure that your code is safe before you deploy it. Before you release your code to the production, make sure that you have tested it thoroughly to avoid runtime security vulnerabilities.
  • You must be aware of which methods and properties are safe to use and those that are unsafe.
  • Use the static checked method instead of the unsafe method to check the validity of a value before returning it and thwart any security issues.

What are Use Cases for Unsafe Code?

In C#, unsafe code allows developers to access the underlying hardware of your computer system, directly bypassing the safety checks that would normally be enforced by the CLR. In C#, unsafe code is also useful when working with pointers, which are essentially references to data that can be stored in memory at any address on the heap.

What is a Pointer in C#?

A pointer is defined as a variable that can point to a memory location. In other words, it contains the memory address of an object. A pointer must have an identical data type as the variable it refers to. As a result, for a pointer to point to the memory location of an integer variable, the pointer’s type must be an integer.

When you create a pointer, you inform the compiler to create a variable that will store the address of another variable in the memory. Note that pointers are essential in C# for working with unsafe code. Unsafe code is code that can access and modify the memory address of other variables.

By using pointers, you can safely access and modify the memory addresses of variables. Pointers are used to access the contents of a memory location. Pointers are also used to pass data between functions, manipulate data structures and implement linked lists.

Read: Productivity Tools for .NET Developers

What are the Benefits and Downsides of Unsafe Code

The benefits of using unsafe code in C# include:

  • Access memory in ways that are not possible with managed methods.
  • Access memory that is not accessible by any other method.

The downsides of using unsafe code is that it is less efficient because the GC has to work harder to manage it. This is not usually noticeable, but if you are writing code for performance reasons, then there may be better ways to achieve this than writing unsafe code.

How to Program Unsafe Code in C#

When you mark a block of code with the unsafe keyword, it has full access to all types, including pointers and other unmanaged resources.

Refer to the C# code example below, which shows how programmers can use a pointer to point to the base address of an integer variable in the memory:

int myvar = 1;
int *myptr = &myvar;

Refer to the following code snippet that shows how you can display the memory address of a variable using unsafe code in C#:

static void Main(string[] args)
{
    Unsafe
    {
       int myvar = 15;
       int* myptr = &myvar;
       Console.WriteLine 
       ("The memory address of the variable myvar is: " + (int)myptr);
    }
}

Refer to the code snippet given below that demonstrates how you can mark a method with the unsafe keyword:

public unsafe void Process(int* myptr)
{
      *myptr = (*myptr) * 5;
      //Write your custom code here using the pointer 
}

In the preceding source code, note that the value at the location pointed to be the pointer is changed directly.

Best Practices for Using Unsafe Code in C#

The following are best practices to keep in mind when working with unsafe code:

  • Use unsafe code only when absolutely necessary. There are times when it is appropriate to use unsafe code, but don’t turn a blind eye on the performance penalties of using pointers as opposed to value types and reference types.
  • Use pointers only when absolutely necessary. Do not use pointers unless you know what they do and why they are needed. If there is another way of doing things that doesn’t require a pointer, then don’t use a pointer.
  • You must use pointers with care. The last thing you want is for your program to crash because someone else’s poorly written code was using memory that had been freed up by something else or because there was an exception caused due to an invalid pointer address in their program, etc.

Final Thoughts on Unsafe Code in C#

In C#, unsafe code allows developers to allocate and manipulate memory directly. It is often used for manipulating pointers, which are integral to access memory addresses and manage data in memory. Unsafe code is most useful when working with low-level details, such as when you would like to access the memory or any other hardware peripherals in your computer.

By unsafe code, we mean source code that is not properly validated or verified before it is executed. In the long run, this may result in security vulnerabilities and other issues. Hence, it is important to understand the benefits and drawbacks of unsafe code so that you know when it’s appropriate and when not. You should not use unsafe if you are not aware of the performance and security implications.

Read more C# programming tutorials and software development how-tos.

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at http://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read