O'Reilly logo

From Java to C#: A Developer's Guide by Heng Ngee Mok

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required