In C #, sizeof is used to calculate the type size, in bytes. There is such a class:
public class MyUglyClass
{
public char myChar1;
public int myInt;
public char myChar2;
}
On the client, try to use sizeof to calculate the size of this type.
class Program
{
static void Main(string[] args)
{
MyUglyClass m = new MyUglyClass();
m.myChar1 = ‘d‘;
m.myInt = 25;
m.myChar2 = ‘a‘;
Console.WriteLine(sizeof(MyUglyClass));
}
}
Run, error:
○ The first error indicates that sizeof must be used, and the keyword unsafe must be used.
○ The second error indicates that sizeof is invalid for the runtime variable and can only calculate the size of the variable for the compiler.
Change the class to the struct value type.
public struct MyUglyClass
{
public char myChar1;
public int myInt;
public char myChar2;
}
The client is changed to the following:
class Program
{
static void Main(string[] args)
{
MyUglyClass m = new MyUglyClass();
m.myChar1 = ‘d‘;
m.myInt = 25;
m.myChar2 = ‘a‘;
unsafe
{
Console.WriteLine(sizeof(MyUglyClass));
}
}
}
Run, continue to report the error: "Unsafe code will only appear when/unsafe compilation is used ".
Solution: Right-click the project, select Properties, generate, and select "allow Insecure code". Save
Run again. Result: 12
Again, in the Value Type Structure of myuglyclass, the char type is 16 bits, which is equivalent to 2 bytes, the int type is 32 bits, and 4 bits. Myuglyclass type size = 2 + 2 + 4 = 8 bytes, it should be 8 bytes! How can it be 12 bytes?
This involves stack alignment and filling. Take the above example as an example: Originally, Int-type variables on the stack accounted for 4 bytes, and 2 char-type variables accounted for 2 bytes, respectively, after these variables are arranged on the stack, the stack also needs to be aligned, that is, all the smaller bytes of the variable to the maximum bytes of the variable, and fill in the space.
The Red Cross is filled for alignment.
To ignore the padding for alignment, you can use the [structlayout] feature.
[StructLayout(LayoutKind.Auto)]
public struct MyUglyClass
{
public char myChar1;
public int myInt;
public char myChar2;
}
Run again. Result: 8
Conclusion: sizeof applies only to value types and must be used in the unsafe context.
Usage of sizeof in C #