Statement Keywords Fixed, Checked and Unchecked

Fixed Block Type

C# uses a garbage collector to clean up memory leaks and take care of unused data storage variables. Fixed ensures that the variable declared inside it’s block will not be touched by the garbage collector. Because this presents a potential issue with memory leaks the fixed keyword block can only be used in methods declared with the “unsafe” keyword. This requires special permissions that some systems will block. The following is an example from MSDN.

unsafe static void TestMethod()
{

    // Assume that the following class exists. 
    //class Point  
    //{  
    //    public int x; 
    //    public int y;  
    //} 

    // Variable pt is a managed variable, subject to garbage collection.
    Point pt = new Point();

    // Using fixed allows the address of pt members to be taken, 
    // and "pins" pt so that it is not relocated.

    fixed (int* p = &pt.x)
    {
        *p = 1;
    }        

}

Checked Block Type

The checked block type is used to make the compiler check for overflow values on any integer calculations. This is useful when performing an operation on a variable and assigning the result to an integer. The compiler does not detect overflow values on non-static variables, so the checked code block is required to enforce it. Here is a code sample from MSDN.

// If the previous sum is attempted in a checked environment, an  
// OverflowException error is raised. 

// Checked expression.
Console.WriteLine(checked(2147483647 + ten));

// Checked block. 
checked
{
    int i3 = 2147483647 + ten;
    Console.WriteLine(i3);
}

Unchecked Block Type

The unchecked block type will allow an integer assignment to overflow instead of throw an error. An example of this from MSDN. The resulting int1 will be equal to “-2,147,483,639”

unchecked
{
    int1 = 2147483647 + 10;
}
int1 = unchecked(ConstantMax + 10);

(Views: 272)

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.