Search code examples
c#variablesruntimevalue-type

C#: Getting size of a value-type variable at runtime?


I know languages such as C and C++ allow determining the size of data (structs, arrays, variables...) at runtime using sizeof() function. I tried that in C# and apparently it does not allow putting variables into the sizeof() function, but type defintions only (float, byte, Int32, uint, etc...), how am I supposed to do that?

Practically, I want this to happen:

int x;
Console.WriteLine(sizeof(x));   // Output: 4

AND NOT:

Console.WriteLine(sizeof(int)); // Output: 4

I'm sure there's some normal way to get the size of data at runtime in C#, yet google didn't give much help.. Here it is my last hope


Solution

  • To find the size of an arbitrary variable, x, at runtime you can use Marshal.SizeOf:

    System.Runtime.InteropServices.Marshal.SizeOf(x)
    

    As mentioned by dtb, this function returns the size of the variable after marshalling, but in my experience that is usually the size you want, as in a pure managed environment the size of a variable is of little interest.