K
K
kodwi2014-07-17 19:57:26
C++ / C#
kodwi, 2014-07-17 19:57:26

Why sizeof(System.Char) == 2 but Marshal.SizeOf(System.Char) == 1?

What is this ambiguity about the size of the Char type in C#?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Permin, 2014-07-17
@kodwi

msdn.microsoft.com/en-us/library/eahchzkf.aspx
Marshal.SizeOf returns the size after the type has been marshaled, whereas sizeof returns the size as it has been allocated by the common language runtime, including any padding.
and:
msdn.microsoft.com/en-us/library/vstudio/5s4920fa(...
The size of the specified type in unmanaged code.
i.e. sizeof is the size of types in the CLR, and Marshal.SizeOf is the size of the type in unmanaged code,
and the first link has a note about this:
Although you can use the Marshal.SizeOf method, the value returned by this method is not always the same as the value returned by sizeof.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question