Extend Array Class with Append method (this ref)

I'd like to extend System.Array class to do something like that:

public static class Extensions
{
    public static void Append( this byte[] dst, byte[] src)
    {
        Array.Resize<byte>(ref dst, dst.Length + src.Length);
        Array.Copy(src, 0, dst, dst.Length - src.Length,src.Length);
        return;
    }
}

but "this" is not possible to be referenced ... and on return it turn back as at the beginning.

Jon Skeet
people
quotationmark

If you mean "Can I make the first parameter of an extension method a ref parameter?" then the answer is no, you can't. (Not in C#, anyway. IIRC, you can in VB - but I'd advise against it.)

From section 10.6.9 of the C# spec:

The first parameter of an extension method can have no modifiers other than this, and the parameter type cannot be a pointer type.

You'd have to return the array instead:

public static byte[] Append(this byte[] dst, byte[] src)
{
    Array.Resize(ref dst, dst.Length + src.Length);
    Array.Copy(src, 0, dst, dst.Length - src.Length,src.Length);
    return dst;
}

Then call it as:

foo = foo.Append(bar);

It really feels like you want a List<byte> at that point though - and if you're really going to make an extension method like this, at least make it generic:

public static T[] Append<T>(this T[] dst, T[] src)
{
    Array.Resize(ref dst, dst.Length + src.Length);
    Array.Copy(src, 0, dst, dst.Length - src.Length,src.Length);
    return dst;
}

people

See more on this question at Stackoverflow