sizeof(), C# and managed code

  • Thread starter Thread starter Paul
  • Start date Start date
P

Paul

I'm porting a C++ function which reads a file in binary mode, sometimes
reading 2 bytes into an unsigned short, 4 bytes into a long, etc into a C#
implementation. When using the FileStream.Read function, I'd like to code
it to read the size of a C# ushort, for example. The documentation says the
sizeof() is only supported in unsafe mode. Is there any equivalent to
sizeof() that I can use in managed code?
 
Hi Paul,

If you use BinaryReader, you have several methods to read in various
size value types, such as ReadInt16, ReadInt32, ReadDouble, etc.

Thobias Jones
 
Paul said:
The documentation says the
sizeof() is only supported in unsafe mode. Is there any equivalent to
sizeof() that I can use in managed code?

Try the Marshal.SizeOf() method (from the System.Runtime.InteropServices
namespace).

Regards,
Pieter Philippaerts
 
You shouldn't use Marshal.SizeOf() for this operation. I assume that Paul
is trying to read managed types from the file. Marshal.SizeOf() will give
you the unmanaged size which may not be equal to
managed size.

--
Jared Parsons [MSFT]
(e-mail address removed)
This posting is provided "AS IS" with no warranties, and confers no rights.
OR if you wish to include a script sample in your post please add "Use of
included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm"
 
Paul said:
I'm porting a C++ function which reads a file in binary mode, sometimes
reading 2 bytes into an unsigned short, 4 bytes into a long, etc into a C#
implementation. When using the FileStream.Read function, I'd like to code
it to read the size of a C# ushort, for example. The documentation says the
sizeof() is only supported in unsafe mode. Is there any equivalent to
sizeof() that I can use in managed code?

Aside from the other answers, you don't need to use sizeof to find the
size of a ushort - it's *always* 16 bits, just like an int is *always*
32 bits. The C# designers learned from the C experience that leaving
the sizes of primitive data types somewhat ambiguous is a bad idea :)
 
Back
Top