Free mag vol1 | Page 491

CHAPTER 11  ADVANCED C# LANGUAGE FEATURES pointer, you are the one in charge of dealing with the consequences. Given these warnings, when exactly would you need to work with pointer types? There are two common situations: • You are looking to optimize select parts of your application by directly manipulating memory outside the management of the CLR. • You are calling methods of a C-based .dll or COM server that demand pointer types as parameters. Even in this case, you can often bypass pointer types in favor of the System.IntPtr type and members of the System.Runtime.InteropServices.Marshal type. In the event that you do decide to make use of this C# language feature, you are required to inform the C# compiler (csc.exe) of your intentions by enabling your project to support “unsafe code.” To do so at the command line, simply supply the following /unsafe flag as an argument: csc /unsafe *.cs From Visual Studio, you will need to access your project’s Properties page and check the Allow Unsafe Code box from the Build tab (see Figure 11-2). To experiment with pointer types, create a new Console Application project named UnsafeCode and enable unsafe code, and make sure you enable this setting. Figure 11-2. Enabling unsafe code using Visual Studio The unsafe Keyword When you wish to work with pointers in C#, you must specifically declare a block of “unsafe code” using the unsafe keyword (any code that is not marked with the unsafe keyword is considered “safe” automatically). For example, the following Program class declares a scope of unsafe code within the safe Main() method: 431