In Delphi, one can do the following:
var
ms : TMemoryStream;
i : Integer;
begin
ms := TMemoryStream.Create;
i := 1024;
ms.Write(@i, SizeOf(Integer));
ms.Free;
end;
This will write the memory contents of i into ms.
The .Net version of MemoryStream doesn’t have such a feature (neither the managed nor unmanaged versions). I know .Net doesn’t work on the same principles as Delphi in this regard.
How does one do this in C#? I am interested in the “best practice” and the fastest methods.
Try using BinaryWriter on top of MemoryStream:
Note: don’t forget to Dispose streams and writers/readers in real code, i.e. by
using.