Translate from C to C# I have been working on translating some code from C to C# but since I haven't been coding in C / C++ for many years now plus I do not want to resort to the unsafe keyword. I have made an attempt and would like some verification &amp; optimisation suggestions.

Here is the code in C/C++.

#ifdef __cplusplus /* C++ cannot assign void* from malloc to *data */
#define APPEND_DATA(/* T */ value, /* T** */ data, /* size_t* */ size) {\
  if (!((*size) &amp; ((*size) - 1))) {\
    /*double alloc size if it's a power of two*/\
    void** data_void = reinterpret_cast&lt;void**&gt;(data);\
    *data_void = (*size) == 0 ? malloc(sizeof(**data))\
                              : realloc((*data), (*size) * 2 * sizeof(**data));\
  }\
  (*data)[(*size)] = (value);\
  (*size)++;\
}
#else /* C gives problems with strict-aliasing rules for (void**) cast */
#define APPEND_DATA(/* T */ value, /* T** */ data, /* size_t* */ size) {\
  if (!((*size) &amp; ((*size) - 1))) {\
    /*double alloc size if it's a power of two*/\
    (*data) = (*size) == 0 ? malloc(sizeof(**data))\
                           : realloc((*data), (*size) * 2 * sizeof(**data));\
  }\
  (*data)[(*size)] = (value);\
  (*size)++;\
}
#endif


Here is the code in C#:

public static T[] AppendData&lt;T&gt;(T value, T[] data, ref uint size)
{
    if ((size &amp; (size - 1)) != 0)
    {
        /* Double alloc size if it's a power of two */
        var tsize = size == 0 ? data.Length : size*2*data.Length;
        var tdata = new T[tsize];
        Array.Copy(data, tdata, data.Length);
        tdata[size] = value;
        data = tdata;
    }
    else
    {
        data[size] = value;
    }

    size++;
    return data;
}


One more thing to note is that performance is paramount for this code as the overall algorithm it fits in to is quite slow.
From a micro-optimization perspective I have found that C# and the JIT tend to like things from left to right (post).
Ex: (((size - 1) &amp; size) != 0) and data.Length*size*2

With a macro and readability (verification) perspective I would be curious to see the performance difference between this method and just using List&lt;T&gt;.Add.

When it comes to performance you need to just measure it. On different machines if you can.