sizeof(), C# and managed code

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?
 
T

Thobias Jones

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
 
P

Pieter Philippaerts

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
 
J

Jared Parsons [MSFT]

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"
 
J

Jon Skeet [C# MVP]

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 :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top