29.10. Using the sizeof operator

This operator returns the number of bytes (also known as the size) occupied by a variable of a given type. You can only use the sizeof operator in an unsafe context marked with the unsafe keyword. The operand to sizeof must be one of the unmanaged types.

An example of sizeof's use is shown below. Remember to compile with the /unsafe option if you are using csc.exe.

 1: using System;
 2:
 3: class MyClass{
 4:
 5:   public static void Main(){
 6:     unsafe{
 7:       Console.WriteLine(sizeof(int));
 8:       Console.WriteLine(sizeof(double));
 9:       Console.WriteLine(sizeof(MyStruct));
10:       }
11:     }
12:   }
13:
14: struct MyStruct {
15:   int i;
16:   double d;
17: }

Output:

c:expt>test
4
8
16

The output shows that the int and double type take up four and eight bytes respectively (which correspond to the information in Table 9.2). It also shows that user-defined struct type MyStruct takes up 16 bytes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.50.87