Monday, February 2, 2009

UnSafe Code in C#

Hi,
Here is some details about Unsafe in C#
Unsafe code is code which does not executed under full control of CLR. It can cause some problems therefore each use must be marked as "unsafe".
...
unsafe
{
...
// unsafe context: can use pointers here
...
}
...
Generally speaking when you write any program in C# you create managed code. Managed code is executed under the control of Common Language Runtime (CLR). CRL causes that programmer do not need to manage memory and take care about memory's allocation and deallocation. CLR also allows you to write what is called 'unsafe code'.

Advantages:

  • Performance and flexibility, by using pointer you can access data and manipulate it in the most efficient way possible.
  • Compatibility, in most cases we still need to use old windows APIs, which use pointers extensively. Or third parties may supply DLLs that some of it’s functions need pointer parameters. Although this can be done by using DLLImport and System.IntPtr class, but in some cases it’s just much simpler to use pointer.
  • Memory Addresses, there is no way to know the memory address of some data without using pointers.

Disadvantages:

  • Complex syntax, to use pointers you need to go throw more complex syntax than we used to experience in C#.
  • Harder to use, you need be more careful and logical while using pointers, miss using pointer might lead to the following:
    • Overwrite other variables.
    • Stack overflow.
    • Access areas of memory that doesn’t contain any data as they do.
    • Overwrite some information of the code for the .net runtime, which will surely lead you application to crash.
  • Type-safety, using pointers will cause the code to fail in the .net type-safety checks, and of course if your Security policy don’t allow non type-safety code, then the .net framework will refuse to execute it.

No comments: