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.
}
}
}
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With