Introduction
The purpose of this article is to understand different behaviours in Marshal.SizeOf
and sizeof
operator for boolean and char data types in C#
sizeof operator
The sizeof
operator takes a type name and tells you how many bytes of managed memory need to be allocated for instance of struct. The sizeof
operator in C# works only on compile-time known types, not on variables (instances)
Marshal.SizeOf operator
Marshal.SizeOf
takes either a type object or an instance of the type, and tells you how many bytes of unmanaged memory need to be allocated. Marshal.SizeOf
can be used on any object instances or runtime types.
Code
The inline code below explains the difference in the bytes for int
and char
types based on the understanding in the introduction section.
//Rextester.Program.Main is the entry point for your code. Don't change it.
//Microsoft (R) Visual C# Compiler version 2.9.0.63208 (958f2354)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
// The sizeof operator takes a type name and tells you how many bytes of managed memory need to be
// allocated for instance of struct
// The sizeof operator in C# works only on compile-time known types, not on variables (instances)
Console.WriteLine(sizeof(bool));
// Outputs 1
Console.WriteLine(sizeof(char));
// Outputs 2
// depends on the char set
// Marshal.SizeOf takes either a type object or an instance of the type, and tells you how many
// bytes of unmanaged memory need to be allocated.
// Marshal.SizeOf which can be used on any object instances or runtime types
Console.WriteLine(Marshal.SizeOf(typeof(bool)));
// Outputs 4
// C didn't have bool denoted by integer
Console.WriteLine(Marshal.SizeOf(typeof(char)));
// Outputs 1
// C uses a single byte to store a character
}
}
}