What is difference between unsafe code and unmanaged code in C#?
Unsafe code in C# allows the use of pointers. In the context of the CLR, there is no unmanaged code in C#.
Unsafe code runs inside the CLR while un-managed code runs outside the CLR.
An example of unsafe code would be:
unsafe class MyClass
{
private int * intPtr;
}
You can use pointers anywhere in this class.
An example of unmanaged code is:
class MyClass
{
[DllImport("someUnmanagedDll.dll")]
static extern int UnManagedCodeMethod(string msg, string title);
public static void Main()
{
UnManagedCodeMethod("calling unmanaged code", "hi");
}
}
It is not necessarily unmanaged code itself, but calling it.
managed code runs under supervision of the CLR (Common Language Runtime). This is responsible for things like memory management and garbage collection.
So unmanaged simply runs outside of the context of the CLR. unsafe is kind of "in between" managed and unmanaged. unsafe still runs under the CLR, but it will let you access memory directly through pointers.
Unsafe - Code that can be outside the verifiable subset of CIL
Unmanaged - Code that is not managed by the runtime and is thus not visible to the GC (for example a native compiled x86 function would be unmanaged.)
from: http://forums.devx.com/archive/index.php/t-15405.html
Here is what you can do inside of an unsafe context.
http://msdn.microsoft.com/en-us/library/aa664769%28v=VS.71%29.aspx