Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make any difference to use unsafe inside or outside a loop?

Tags:

c#

unsafe

I never needed to use unsafe in the past, but now I need it to work with a pointer manipulating a bitmap.

I couldn't find any documentation that indicates otherwise, but I would like to understand better how unsafe works and if it makes any difference to use it inside or outside a loop.

Is it better to do:

unsafe
{
    for (int x = 0; x < maxX; x++)
    {
        for (int y = 0; y < maxY; y++)
        {           
            //Unsafe pointer operations here.
        }
    }
}

Or to do?:

for (int x = 0; x < maxX; x++)
{
    for (int y = 0; y < maxY; y++)
    {   
        unsafe
        {       
            //Unsafe pointer operations here.
        }
    }
}
like image 525
Dzyann Avatar asked Jan 22 '16 14:01

Dzyann


People also ask

What does unsafe code mean?

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.


2 Answers

unsafe keyword is a marker that you use to tell the compiler that you know what you are doing. Its main purpose is similar to documenting your code: unsafe block shows parts of your code that you designate as unmanaged territory; there is no impact on the actual execution of code.

With this in mind, it makes sense to reduce the size of this unsafe territory as much as possible, which means that your second approach is better than the first one.

It is worth mentioning that two other alternatives, i.e. marking the method and marking the class with unsafe, are also inferior to the approach when the unsafe block is placed around the smallest possible portion of the code.

like image 111
Sergey Kalinichenko Avatar answered Oct 10 '22 08:10

Sergey Kalinichenko


unsafe changes which expressions the compiler will accept and produce output for. It imposes no runtime overhead, in and of itself. For any expression that doesn't require unsafe, the compiler will emit the same code whether its within an unsafe context or not.

For the specifics of which expressions can only be used within an unsafe context, I'd recommend consulting section 18 of the C# Language Specification

like image 25
Damien_The_Unbeliever Avatar answered Oct 10 '22 07:10

Damien_The_Unbeliever