Unsafe Code in C#

Unsafe code is formally denoted as unmanaged code .NET. Unmanaged codes as the possibility to use the pointers in the .NET managed code. Basically .NET hides most of the memory management; it makes all the .NET programmer and developers easier for development. Commonly there is need to use the unsafe code in our application while using Microsoft .NET.

When and why should we need this unsafe or unmanaged code in .NET? The answer is if you want to access memory mapped devices or if you want to create an application that to interface with your operation system, while using pointer to increase your application performance, External functions, in some cases you might need to write an application that analyzes another application process and memory etc, we need this unmanaged code, it will be more advantageous when we use this in those situations.

Some of the main advantages about the unsafe code in .NET are performance and flexibility, compatibility like DLLImport, memory addresses.

Some of the notable disadvantages about the unmanaged code in .NET are Complex to implement in C#, you should be more careful while using pointers in .NET application, miss use of pointer will cause many problems like stack overflow, overwrite existing or other variables, unauthorized access to memory areas, simple mistake in using pointers might lead your application to crash randomly and unpredictably, using pointers will cause the code to fail in the .net type-safety checks.

Sample unmanaged code snippet:

DllImport("shell32.dll", SetLastError = true)]
extern public static bool
ShellExecuteEx(ref ShellExecuteInfo lpExecInfo);
public const uint SW_NORMAL = 1;
static void OpenAs(string file)
ShellExecuteInfo sei = new ShellExecuteInfo();
sei.Size = Marshal.SizeOf(sei);
sei.Verb = "openas";
sei.File = file;
sei.Show = SW_NORMAL;
if (!ShellExecuteEx(ref sei))
throw new System.ComponentModel.Win32Exception();

For more reference


Popular posts from this blog

ASP.NET website "Cannot read configuration file due to insufficient permissions" in IIS 7 and Windows Server 2008

Error occurred in deployment step 'Install app for SharePoint': The System Account cannot perform this action.

Windows Server AppFabric: installation error , While installing SharePoint prerequisite installer