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 ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.