Logo

Programming-Idioms

  • C#

Idiom #109 Number of bytes of a type

Set n to the number of bytes of a variable t (of type T).

int n = sizeof(T);

n is the size in managed memory of built-in value type (numeric types, char, and bool) T. Permitted in safe contexts.

In a safe context, sizeof is only permitted for built-in value types. Because there is no corresponding type parameter constraint, the operand of_sizeof cannot be a type parameter in a safe context.
using System.Runtime.InteropServices;
int n = Marshal.SizeOf(t);

Marshal.SizeOf() returns the size of a type or object if it were to be marshalled to unmanaged memory.
int n;
unsafe
{
    n = sizeof(T);
}

n is the size in managed memory of unmanaged type T or type parameter T constrained to unmanaged types.

Unmanaged types are built-in value types, enums, pointers, and structs with fields that are all unmanaged types.
N : Integer := (T'Size + 7) / 8;

T'Size returns size of T in bits. It is the minimum number of bits required to store an object of that type.
Divide by 8 to convert to bytes

New implementation...
< >
programming-idioms.org