Search code examples
c#delphiequivalent

What is the equivalent of Delphi "ZeroMemory" in C#?


In delphi the "ZeroMemory" procedure, ask for two parameters.

CODE EXAMPLE

procedure ZeroMemory(Destination: Pointer; Length: DWORD);
begin
 FillChar(Destination^, Length, 0);
end;

I want make this, or similar in C#... so, what's their equivalent?

thanks in advance!


Solution

  • .NET framework objects are always initialized to a known state

    .NET framework value types are automatically 'zeroed' -- which means that the framework guarantees that it is initialized into its natural default value before it returns it to you for use. Things that are made up of value types (e.g. arrays, structs, objects) have their fields similarly initialized.

    In general, in .NET all managed objects are initialized to default, and there is never a case when the contents of an object is unpredictable (because it contains data that just happens to be in that particular memory location) as in other unmanaged environments.

    Answer: you don't need to do this, as .NET will automatically "zero" the object for you. However, you should know what the default value for each value type is. For example, the default of a bool is false, and the default of an int is zero.

    Unmanaged objects

    "Zero-ing" a region of memory is usually only necessary in interoping with external, non-managed libraries.

    If you have a pinned pointer to a region of memory containing data that you intend to pass to an outside non-managed library (written in C, say), and you want to zero that section of memory, then your pointer most likely points to a byte array and you can use a simple for-loop to zero it.

    Off-topic note

    On the flip side, if a large object is allocated in .NET, try to reuse it instead of throwing it away and allocating a new one. That's because any new object is automatically "zeroed" by the .NET framework, and for large objects this clearing will cause a hidden performance hit.