The topics described here concentrates fully on pure .Net Framework, describing actual meaning of some programming concepts, FCL and best practices. However you will be using these concepts in all . Net framework compatible languages like Microsoft visual basic .net (VB.Net) or C# .Net (csharp.Net) to build a web application (Asp.Net) or Desktop applications (winforms .net) or Web/Windows services





This blog has moved!

You will be automatically redirected to the new address. If that does not occur, visit
http://Codemine.net
and update your bookmarks.

Thursday, July 12, 2007

Type Safety and unsafe Code

Safe code is code that is verifiably safe. That is, runtime can verify and make sure that it is not referring to inappropriate memory or memory of the wrong type. If we want to work directly with memory addresses and can manipulate bytes at these addresses then we have to declare that code chunk as unsafe using the unsafe Keyword in C#. So that CLR will not do any do any extra verification on this code and it is really possible to verify this code by CLR even if it is required.

Thus the unsafe just means that it is unverifiable by the runtime. And the normal managed code which is verifiable in every means is called the Type Safe code.

All methods that contain unsafe code should be marked with the unsafe keyword. In
addition, the C# compiler requires you to compile the source code by using the /unsafe
compiler switch.

When the JIT compiler attempts to compile an unsafe method, it checks to see if the assembly containing the method has been granted the System.Security.Permissions.Security-Permission with the System.Security.Permissions.SecurityPermission Flag's
SkipVerification flag set. If this flag is set, the JIT compiler will compile the unsafe code and allow it to execute. The CLR is trusting this code and is hoping the direct address and byte manipulations do not cause any harm. If the flag is not set, the JIT compiler throws either a System.InvalidProgramException or a System.Security.VerificationException, preventing the method from executing

All Normal managed code are labeled as type safe by default because it will be using the .Net provided libraries and classes for accomplishing the task

Microsoft supplies a utility called PEVerify.exe, which examines all of an assembly's methods
and notifies you of any methods that contain unsafe code. This will let you know if there may be
Problems running your application via the intranet or Internet

0 comments: