X hits on this document





330 / 396

Chapter ‎18   Unsafe code

public unsafe struct Node { public int Value; public Node* Left; public Node* Right; }

the unsafe modifier specified in the struct declaration causes the entire textual extent of the struct declaration to become an unsafe context. Thus, it is possible to declare the Left and Right fields to be of a pointer type. The example above could also be written

public struct Node { public int Value; public unsafe Node* Left; public unsafe Node* Right; }

Here, the unsafe modifiers in the field declarations cause those declarations to be considered unsafe contexts.

Other than establishing an unsafe context, thus permitting the use of pointer types, the unsafe modifier has no effect on a type or a member. In the example

public class A { public unsafe virtual void F() { char* p; ... } }

public class B: A { public override void F() { base.F(); ... } }

the unsafe modifier on the F method in A simply causes the textual extent of F to become an unsafe context in which the unsafe features of the language can be used. In the override of F in B, there is no need to re-specify the unsafe modifier—unless, of course, the F method in B itself needs access to unsafe features.

The situation is slightly different when a pointer type is part of the method’s signature

public unsafe class A { public virtual void F(char* p) {...} }

public class B: A { public unsafe override void F(char* p) {...} }

Here, because F’s signature includes a pointer type, it can only be written in an unsafe context. However, the unsafe context can be introduced by either making the entire class unsafe, as is the case in A, or by including an unsafe modifier in the method declaration, as is the case in B.

18.2 Pointer types

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.317

Document info
Document views467
Page views467
Page last viewedSun Oct 23 08:40:35 UTC 2016