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

后端 未结 7 2043
暗喜
暗喜 2020-11-30 08:41

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 i

7条回答
  •  星月不相逢
    2020-11-30 09:33

    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.

提交回复
热议问题