What is the need for unsafe code in C#?If you were
using C, C++ languages before developing applications using C#, then you
would have extensively used pointers. Hence while using C#, you might
find it difficult to get rid of pointers completely and of course there
might be situations which require direct accessing of memory.
In such justifiable scenarios, C# allows you to use pointers but with a restriction that the code using pointers should be wrapped inside an unsafe code block. Not just a code block, an entire method or even a single line of code can be marked as unsafe. Here is an example demonstrating usage of unsafe code block: public class
sampleClass { In this code, you use a pointer to point to address of an integer. When you execute this code, you will end up in the following error: Unsafe code may only appear if compiling with /unsafe This is because
using unsafe code might be harmful because memory is directly accessed.
Hence while compiling the User should be aware that unsafe code is present
in the program. For that, User is asked to explicitly compile such program
with /unsafe option as shown below:
|