c# – Analog of the sizeof operator from C ++ to C #


C ++ has a sizeof operator. Is there something like this in C # ?


The System.Runtime.InteropServices.Marshal class has a SizeOf method that accepts a System.Type parameter (there is also a generic version), but it cannot be used with classes (reference types), which is generally logical, for example:

using System;    
using System.Runtime.InteropServices;

struct MyStruct { int a; int b; }

struct MyStructWithArray { int a; int b; int[] c; }

class MyClass { }

public class Program
    public void Main()
        Console.WriteLine(Marshal.SizeOf<MyStruct>()); //8
        Console.WriteLine(Marshal.SizeOf(typeof(MyStructWithArray))); //16
        Console.WriteLine(Marshal.SizeOf<MyClass>()); //System.ArgumentException

PS The sizeof operator can only be used with primitive C # types (int, byte …)

Scroll to Top