top
Easter Sale

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 *

Comments

austin faith

Avery good write-up. Please let me know what are the types of C# libraries used for AI development.

kariya arti

very satisfied!!

jean-Francois Michaud

Good tutorial. Small question: Say, there is : enum numbers { one, two, three} and a string field_enum ="one" how would I from the variable field_enum have a response with value numbers.one so that it can be treated as an enum and not as a string. making a list from the enum, and loop into the list. is not elegant... and may not work is forced value on field is forced ( one = 100).

Kshitiz

Hi Team Knowledge Hut, Thank you for such an informative post like this. I am completely new to this digital marketing field and do not have much idea about this, but your post has become a supportive pillar for me. After reading the blog I would expect to read more about the topic. I wish to get connected with you always to have updates on these sorts of ideas. Regards, Kshitiz

Ed

The reason abstraction can be used with this example is because, the triangle, circle. Square etc can be defined as a shape, for example.....shape c = new circle(5,0)...the abstract object c now points at the circle class. Thus hiding implementation

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