ECMA-334 C# Language Specification25.1: Unsafe contexts |
The unsafe features of C# are available only in unsafe contexts. An unsafe context is introduced by including an unsafe modifier in the declaration of a type or member, or by employing an unsafe-statement:
unsafe-statement enables the use of an unsafe context within a block. The entire textual extent of the associated block is considered an unsafe context. The associated grammar extensions are shown below. For brevity, ellipses (...) are used to represent productions that appear in preceding chapters.
... ... ... ... ... ... ... ... ... ... ... attributesoptextern optunsafe opt ~ identifier ( ) destructor-body attributesoptunsafe optextern opt ~ identifier ( ) destructor-body attributesoptextern optunsafe optstatic identifier ( ) static-constructor-body attributesoptunsafe optextern optstatic identifier ( ) static-constructor-body ... unsafe-statement block
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 unsafe struct Node
{
public int Value;
public Node* Left;
public Node* Right;
}
public struct Node
{
public int Value;
public unsafe Node* Left;
public unsafe Node* Right;
}
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.
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.
public class A
{
public unsafe virtual void F() {
char* p;
...
}
}
public class B: A
{
public override void F() {
base.F();
...
}
}
public unsafe class A
{
public virtual void F(char* p) {...}
}
public class B: A
{
public unsafe override void F(char* p) {...}
}