top

Search

C# Tutorial

Unsafe code in general is a keyword that denotes a code section that is not handled by the Common Language Runtime(CLR). Pointers are not supported by default in C# but unsafe keyword allows the use of the pointer variables.However, extra care is required while handling unsafe code to prevent errors or security risks as pointers are complex and may lead to memory related errors such as stack overflow, overwritten system memory etc.Using Unsafe Code in Visual Studio IDEUnsafe code can be used in Visual Studio IDE by following the given steps:Double click properties in the Solution Explorer to open project properties.Click the Build tab and select the option “Allow Unsafe Code”.This enables the usage of unsafe code in Visual Studio IDE.Examples of Unsafe CodeSome of the examples of unsafe code implementing pointers are given as follows:Example 1A program that demonstrates the pointer declaration and data reference using pointers is given as follows:Source Code: Program to demonstrate pointer declaration and data reference using pointers in C#using System; namespace PointerDemo {   class Example   {      static unsafe void Main(string[] args)      {         char val = 'A';         char* ptr = &val;         Console.WriteLine("The character value is: {0} ", val);         Console.WriteLine("Address of the value is: {0}", (int)ptr);      }   } }The output of the above program is as follows:The character value is: A Address of the value is: 220412608Now let us understand the above program.The character variable val contains A. Pointer ptr points to val i.e. it contains the address of val. Then the values of val and ptr are displayed. The code snippet for this is given as follows:char val = 'A';         char* ptr = &val;         Console.WriteLine("The character value is: {0} ", val);         Console.WriteLine("Address of the value is: {0}", (int)ptr);Example 2If a pointer is required to access array elements in C#, then the fixed keyword is used. This is because the array and the pointer data type are not the same. For example: The data type int[] is not the same as int*.A program that demonstrates accessing array elements using pointers is given as follows:using System; namespace UnsafeCodeApplication {   class TestPointer {      public unsafe static void Main() {         int[] arr = {10, 7, 13, 54, 99};         fixed(int *ptr = arr)         for ( int i = 0; i < 5; i++)         {            Console.WriteLine("arr[{0}] = {1}", i, *(ptr + i));         }      }   } }The output of the above program is as follows:arr[0] = 10 arr[1] = 7 arr[2] = 13 arr[3] = 54 arr[4] = 99Now let us understand the above program.The array arr contains 5 values of type int. The pointer ptr points to the start of the array using the fixed keyword. Then all the array values are displayed using for loop. The code snippet for this is given as follows:int[]  arr = {10, 7, 13, 54, 99};         fixed(int *ptr = arr)         for ( int i = 0; i < 5; i++)         {            Console.WriteLine("arr[{0}] = {1}", i, *(ptr + i));         }
logo

C# Tutorial

Unsafe Code in C#

Unsafe code in general is a keyword that denotes a code section that is not handled by the Common Language Runtime(CLR). Pointers are not supported by default in C# but unsafe keyword allows the use of the pointer variables.

However, extra care is required while handling unsafe code to prevent errors or security risks as pointers are complex and may lead to memory related errors such as stack overflow, overwritten system memory etc.

Using Unsafe Code in Visual Studio IDE

Unsafe code can be used in Visual Studio IDE by following the given steps:

  1. Double click properties in the Solution Explorer to open project properties.
  2. Click the Build tab and select the option “Allow Unsafe Code”.

This enables the usage of unsafe code in Visual Studio IDE.

Examples of Unsafe Code

Some of the examples of unsafe code implementing pointers are given as follows:

Example 1

A program that demonstrates the pointer declaration and data reference using pointers is given as follows:

Source Code: Program to demonstrate pointer declaration and data reference using pointers in C#

using System;
namespace PointerDemo
{
  class Example
  {
     static unsafe void Main(string[] args)
     {
        char val = 'A';
        char* ptr = &val;
        Console.WriteLine("The character value is: {0} ", val);
        Console.WriteLine("Address of the value is: {0}", (int)ptr);
     }
  }
}

The output of the above program is as follows:

The character value is: A
Address of the value is: 220412608

Now let us understand the above program.

The character variable val contains A. Pointer ptr points to val i.e. it contains the address of val. Then the values of val and ptr are displayed. The code snippet for this is given as follows:

char val = 'A';
        char* ptr = &val;
        Console.WriteLine("The character value is: {0} ", val);
        Console.WriteLine("Address of the value is: {0}", (int)ptr);

Example 2

If a pointer is required to access array elements in C#, then the fixed keyword is used. This is because the array and the pointer data type are not the same. For example: The data type int[] is not the same as int*.

A program that demonstrates accessing array elements using pointers is given as follows:

using System;
namespace UnsafeCodeApplication {
  class TestPointer {
     public unsafe static void Main() {
        int[] arr = {10, 7, 13, 54, 99};
        fixed(int *ptr = arr)
        for ( int i = 0; i < 5; i++)
        {
           Console.WriteLine("arr[{0}] = {1}", i, *(ptr + i));
        }
     }
  }
}

The output of the above program is as follows:

arr[0] = 10
arr[1] = 7
arr[2] = 13
arr[3] = 54
arr[4] = 99

Now let us understand the above program.

The array arr contains 5 values of type int. The pointer ptr points to the start of the array using the fixed keyword. Then all the array values are displayed using for loop. The code snippet for this is given as follows:

int[]  arr = {10, 7, 13, 54, 99};
        fixed(int *ptr = arr)
        for ( int i = 0; i < 5; i++)
        {
           Console.WriteLine("arr[{0}] = {1}", i, *(ptr + i));
        }

Leave a Reply

Your email address will not be published. Required fields are marked *

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

Python Tutorial

Python Tutorial