unsafe block : unsafe « unsafe « C# / CSharp Tutorial






public struct MyValue
{
    private int id;
    private decimal price;
    public MyValue(int id, decimal price) 
    {
        this.id = id;
        this.price = price;
    }
    override public string ToString() 
    {
        return String.Format("{0}: {1}", id, price);
    }
   
    unsafe public static void Swap(MyValue* pi, MyValue* pj)
    {
        MyValue tmp = *pi;
        *pi = *pj;
        *pj = tmp;
    }
}
   
class UnsafeStructApp
{
    static void Main(string[] args)
    {
        MyValue i = new MyValue(123, 45.67m);
        MyValue j = new MyValue(890, 98.76m);
        Console.WriteLine("Before Swap:\ti = {0}, j = {1}", i, j);
   
        unsafe { MyValue.Swap(&i, &j); }
        Console.WriteLine("After Swap:\ti = {0}, j = {1}", i, j);
    }
}








36.1.unsafe
36.1.1.Unsafe Code
36.1.2.Compile unsafe code
36.1.3.Using unsafe and fixed
36.1.4.Mark method as unsafe to pointers
36.1.5.Accessing Structure Members with a Pointer
36.1.6.Unsafe Methods
36.1.7.Using the unsafe keyword.
36.1.8.unsafe block