shrd
shrd

Reputation: 69

how to create an array without objects initialized to null or 0?

byte[] buffer = new byte[500000];

initializes buffer with 0 values. As it is a buffer, I dont want any initialization, is it possible in C# as in C?

Upvotes: 2

Views: 3285

Answers (3)

huysentruitw
huysentruitw

Reputation: 28091

A way in C# to do what malloc does in C is to use Marshal.AllocHGlobal in an unsafe context:

unsafe
{
    var ptr = Marshal.AllocHGlobal(50000 * sizeof(int));
    int* values = (int*)ptr;

    // lists uninitialized ints
    for (int i = 0; i < 50000; i++)
        Console.WriteLine(values[i]);

    Marshal.FreeHGlobal(ptr);
}

Upvotes: 1

i486
i486

Reputation: 6564

Fill it with random numbers or use DllImport and VirtualAlloc from Win32 API.

Upvotes: 0

xanatos
xanatos

Reputation: 111830

I don't think it is possible... Even FormatterServices.GetUninitializedObject that doesn't run constructors:

Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object.

Note that if you want unmanaged (memory taken from the OS that isn't GC-managed), that can be allocated without zeroing it, but it wouldn't be a byte[].

Upvotes: 1

Related Questions