Understand unsafe block and low level programming in C#

Sourav.Kayal
Posted by in C# category on for Beginner level | Points: 250 | Views : 3232 red flag

How to write low level code within "unsafe" block

Understand unsafe block and low level programming in C#

If you have programming experience in C or C++ then probably you know the concept of low level programming. In low level programming we can directly talk with system hardware. For example we can control the process or can allocate memory according to our need. For this low level features C and C family language is used to control various hardware. In C++ also we can get the test of low level programming. Now, we all know that C# is high level object oriented programming language, but in spite of high level language, it has few low level features. We can write low level code in C# programming language. In this article we will see how to do that.

To write low level code we have to know two things. The first one is “All low level code should place within unsafe block”

The structure of unsafe block
unsafe{
}

And the second one is “We have to allow compiler to compile unsafe code” . Here is the setting in VisualStudio.

Go to project’s property->Go to “Build” option->Check the allow unsafe checkbook. Here is screenshot of settings.


Now compile will allow writing low level code in .NET application using C#. So, let’s start with few examples.  Have a look on below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp
{
   class Program
    {
     
        static void Main(string[] args)
        {
            unsafe
            {
                int a =100;
                int* p = &a;
                Console.WriteLine("Value of a is :- " + *p);
            }
            Console.ReadLine();
        }
    }
}

In this example we have define one unsafe block at first and within unsafe block we have define one integer variable and another integer pointer. The beauty of integer pointer is , it can able to store the address of integer variable. We are storing the address of variable a within integer pointer by below code.

Int *p = &a;

The ‘&’ operator is called address of operator, which returns address of any variable. Then within Console.WriteLine() function we are printing the value of variable ‘a’ with the help of pointer ‘p’ .Note that to get the value of specific pointer we are using “*” operator, which is nothing but “value at the address operator”.

Here is output


Get address of variable

With the help of pointer, we can get the memory address of any variable. Have a look on below code and for that

we have to use stackalloc keyword.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApp
{
   class Program
    {
        static void Main(string[] args)
        {
            unsafe
            {
                int a = 200;
                int* p = &a;
                Console.WriteLine("Address of a is:- " + (int)p);
            }
            Console.ReadLine();
        }
    }
}

Here is output.


Allocate memory onto stack

In this example we will allocate memory onto stack and then we will push few dummy value onto it. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApp
{
   class Program
    {
       unsafe public static void Print(int* pa)
       {
           for (int* ip = pa; ip < (pa + 5); ip++)
           {
               Console.WriteLine("value {0} at the address: {1}", *ip, (int)ip);
           }
       }
 
        static void Main(string[] args)
        {
            unsafe
            {
                //Allocate memory on stack
                int* p = stackalloc int[5];
                //Set Value into memory
                p[0] = 10;
                p[1] = 20;
                p[2] = 30;
                p[3] = 40;
                p[4] = 50;
                Print(p);
            }
            Console.ReadLine();
        }
    }
}

Here is sample output


conclusion:-

In this article we have seen how to write low level code in .NET environment within "unsafe" block. Basically low level programming is used to control the hardware. Hope you have understood it.


Page copy protected against web site content infringement by Copyscape

About the Author

Sourav.Kayal
Full Name: Sourav Kayal
Member Level: Silver
Member Status: Member,MVP
Member Since: 6/20/2013 2:09:01 AM
Country: India
Read my blog here http://ctrlcvprogrammer.blogspot.in/
http://www.dotnetfunda.com
I am .NET developer working for HelixDNA Technologies,Bangalore in healthcare domain. Like to learn new technology and programming language. Currently working in ASP.NET ,C# and other microsoft technologies.

Login to vote for this post.

Comments or Responses

Posted by: Longwest on: 7/14/2015 | Points: 25
Hi, Sourav
Thank you for giving this guide.

Best regards.
http://www.keepdynamic.com/

Login to post response

Comment using Facebook(Author doesn't get notification)