tags:

views:

163

answers:

5

What is difference between unsafe code and unmanaged code in C#?

+2  A: 

Unsafe code in C# allows the use of pointers. In the context of the CLR, there is no unmanaged code in C#.

Matthew Ferreira
I've always understood 'unmanaged' code as code that doesn't execute in the context of the CLR... Basically like calls to C/C++ DLLs and such.
J J
I totally agree. You won't be P/Invoking any C# DLLs though, just C/C++ ones as you mentioned.
Matthew Ferreira
A: 

Unsafe - Code that can be outside the verifiable subset of MSIL

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

Hal
you use something like pinvoke to run unmanaged code in .net
Hal
@Hal: Yes, but you can also define extern functions with DLLImport attributes to bring in and hook to native DLLs; a class of extern function handles can be used as a managed "wrapper" to the native code.
KeithS
+1  A: 

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.

Shawn Mclean
+10  A: 

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.

NullUserException
@NullUserExceptin : thank you , it really useful for me
ashish
What do you mean by "context"? With C++/CLI, you can mix managed and unmanaged (native) code in one assembly, in one process.
nikie
A: 

Here is what you can do inside of an unsafe context.

http://msdn.microsoft.com/en-us/library/aa664769%28v=VS.71%29.aspx

High