This program (1st one) is given in the following website.
http://www.dotnetperls.com/unsafe
When I tried to compile error message is "Unsafe code may only appear if compiling with /unsafe". Please explain the reason.
using System;
class Program
{
unsafe static void Main()
{
fixed (char* value = "sam")
{
char* ptr = value;
while (*ptr != '\0')
{
Console.WriteLine(*ptr);
++ptr;
}
}
}
}
Loading
Posted Oct 9, 2013, 3:22 PM
VulpesPosted Oct 9, 2013, 9:18 AM
1. Improve performance.
2. Interoperate with unmanaged code written in C/C++.
3. Interface with the operating system.
4. Access memory-mapped devices.
Regarding #1, one reason why managed code executes more slowly than C/C++ code is because of the need to check that string and array accesses are always within bounds. C# can avoid bounds checking by using unsafe code, thereby improving performance, but at the obvious expense of code being less safe.
Posted Oct 9, 2013, 8:50 AM
What is the practical benefits of unsafe code?
VulpesPosted Oct 9, 2013, 8:27 AM
When the /unsafe switch is used, the C# compiler automatically includes this attribute in the resulting assembly:
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification=true)]
The CLR's JIT compiler checks for the presence of this attribute before compiling and executing a method containing unsafe code. If it's not present an exception is thrown.
Sanjeeb LenkaPosted Oct 9, 2013, 7:11 AM
If you want compile the unsafe code in VS, you should set the project's properties(you can see the properties when you right click the project). Enable the 'Allow unsafe code' selection under 'Build' tab.
If you compile it in command-line,you could use the /usafe switch compile.I hope this will help resolve your problem.
or
check this link
http://kishordgupta.wordpress.com/2011/02/06/how-to-allow-unsafe-code-in-visual-studio-2010-c/