Unsafe keyword PDF Print E-mail
User Rating: / 0
PoorBest 
Monday, 09 March 2009
HTML clipboard

The unsafe keyword denotes an unsafe context. A unsafe context is required for any operations that you want to perfrom with pointers. unsafe is applied as a modifier in the declaration of callable member such as methods, properties, constructors and extenders (although static constructors are not permitted).

static unsafe void ComplexOp()
{
    //unsafe context with use of pointers here
}
The scope of the unsafe includes the parameter list to the end of the function, thus allowing pointers in the parameter list such as:

static unsafe void ComplexOp(byte* ps, int count)
{
    //unsafe context with use of pointers here
}
Note: When compiling unmanaged code you have to specify the /unsafe compiler switch.

Example:

// unsafe keyword
using System;

class UnSafe
{
    // unsafe method that takes a pointer to integer (int)
    unsafe static void AddPtr (int* p)
    {
        *p += *p;   
    }

    unsafe public static void Main()
    {
        int iApples = 10;
        AddPtr(&iApples);
        Console.WriteLine(iApples);
       
        // pauses output window
        Console.ReadLine();
    }

}

 
< Prev   Next >
School Joomla Templates and Joomla Tutorials