
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
1065
Chapter 19
CHAPTER 19
Unsafe Code
19.0 Introduction
Visual C# .NET allows you to step outside of the safe environment of managed code
and write code that is considered “unsafe” by the CLR. Running unsafe code pre-
sents a certain set of restrictions in exchange for opening up possibilities, like access-
ing memory-mapped data or implementing time-critical algorithms that use pointers
directly. These restrictions are mainly based in the CAS system of the CLR and are in
place to draw a distinct line between code the CLR knows to be playing by the rules
(or “safe”) and code that needs to do a bit outside of the traditional sandbox of the
CLR (and is thus “unsafe” code). In order to run code that is marked as unsafe by the
CLR, you need to have the CAS
SkipVerification privilege granted to the assembly
where the unsafe code is implemented. This tells the CLR to not bother verifying the
code and to allow it to run, whereas normally unverified code would not run. This is
a highly privileged operation and is not to be done lightly, as you increase the per-
missions your application will require in order to operate correctly on a user’s sys-
tem. If you use unsafe types in a method signature, you also make the code non-CLS-
compliant. This means that interoperability with other .NET-based