Unsafe Code

While as a managed platform code on .NET is normally inherently type safe, a special Unsafe Code option can be enabled to allow the writing of code that can do more direct (and, unsafe) operations, such as direct memory manipulation via pointers.

Here, "Unsafe" means that the code cannot be verified by the runtime, ands thus could lead to more severe crashes than regular code. For this reason, unsafe code may not be allowed in all execution contexts (such as for example for code hosted in SQL Server, or when running apps from a network drive. Unsafe code does not have any other speed or runtime consequences.

In order to use unsafe code, the "Allow Unsafe Code" Compiler Option need to be enabled and each method that uses unsafe code must be marked with the unsafe modifier, available in Oxygene and C#.

In C#, the unsafe keyword is also required on the class itself, if it contains fields opr properties of unsafe (e.g. pointer) types. In Oxygene, this is not required.

To use unsafe code, apply the unsafe keyword:

type
  MyClass = public class
  private
    fData: ^Byte;
  public
    method WorkWithData; unsafe;
    begin
      fData^ := fData^ + 1;
    end;   
  end;
public unsafe class MyClass
{
    private byte *data;
    
    public unsafe void WorkWithData()
    {
      *data = (*data)+1;
    }
}

Support for unsafe code is currently only available in Oxygene and C#.

See Also