29.4. Using the unsafe keyword

Probably the first keyword to learn for unsafe programming is unsafe itself. This is used to demarcate a type, member, or code block which contains unsafe codes. The demarcated code region is known as the unsafe context. A compilation error occurs if unsafe codes appear outside an unsafe context.

The unsafe modifier can be applied to a class, struct, interface, delegate, field, method, property, event, indexer, operator, constructor (both instance and static constructors), or destructor. The following code fragments are examples of how the unsafe keyword is used to create an unsafe context.

10: public unsafe class UnsafeClass{
11:   // unsafe context with class
12: }

20: public class MyClass{
21:   public unsafe int* pValue; // unsafe field
22:   public unsafe void MyMethod () {
23:     // unsafe context within method
24:   }
25: }

30: public class MyClass{
31:   public void MyMethod(){
32:     unsafe{ // unsafe block
33:     // unsafe context within arbitrary code block
34:   }
35:  }
36: }

The following special keywords can only be used in an unsafe context: stackalloc, fixed, and sizeof. Statements containing pointer declarations and operations must only be written in an unsafe context, or a compilation error occurs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.197.93