Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of using unsafe vs safe C# code?

Tags:

c#

unsafe

unsafe static void SquarePtrParam (int* p) 
   {
      *p *= *p;
   }

VS

static void SquarePtrParam (ref int p) 
   {
      p *= p;
   }
like image 543
InfoLearner Avatar asked Mar 22 '11 23:03

InfoLearner


People also ask

What is the use of unsafe C#?

C# supports an unsafe context, in which you may write unverifiable code. In an unsafe context, code may use pointers, allocate and free blocks of memory, and call methods using function pointers. Unsafe code in C# isn't necessarily dangerous; it's just code whose safety cannot be verified.

What is safe and unsafe code in C#?

In general, the code that we write in C# is safe code. It creates managed objects and doesn't access the memory directly. On the other hand, unsafe code in C# is code that is not in direct control of the Common Language Runtime (CLR).

What is unsafe programming?

In an unsafe programming language, errors are not trapped. Rather, after executing an erroneous operation the program keeps going, but in a silently faulty way that may have observable consequences later on.

What is unsafe rust?

All the code we've discussed so far has had Rust's memory safety guarantees enforced at compile time. However, Rust has a second language hidden inside it that doesn't enforce these memory safety guarantees: it's called unsafe Rust and works just like regular Rust, but gives us extra superpowers.


2 Answers

Safe code can run in any situation where you can run C# code (Silverlight, shared hosting ASP.NET, XNA, SQL Server, etc.), while unsafe code require elevated trust. This means you can run your code in more places and with fewer restrictions.

Also, it's safe, meaning you don't have to worry about doing something wrong and crashing your process.

like image 189
Gabe Avatar answered Nov 04 '22 06:11

Gabe


Your example is not a good one, the JIT compiler already generates the code like that. Under the hood references are pointers too. This needed to be fast, managed code would never have been competitive.

The garbage collected heap is pretty incompatible with pointers, you have to pin objects to make it possible to create a pointer to them. Without the pinning, the garbage collector could move the object and your code randomly fails, destroying the heap integrity. Pinning has a non-zero cost, both in the operation and the loss of efficiency you'll suffer, well after you unpinned, when a garbage collection happens while an object is pinned.

Pointers are highly effective when accessing unmanaged memory. The canonical example is image processing that requires accessing the pixels of a bitmap. And it is a way to quickly access pinned arrays with all the safety interlocks removed, array index checking isn't free when you don't iterate them.

like image 45
Hans Passant Avatar answered Nov 04 '22 06:11

Hans Passant