29.10 Using the sizeof operator


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.



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net