-4

I want to write a Method chain to add CRC ( 2 byte ) with byte[]. with internet source, I write this . but not work... with less knowledge,I do not know why... Please help me..

public byte[] AddCrc<T>(this byte[] x)
{
    if (x == null) throw new ArgumentNullException("x");
    int oldLen = x.Length;
    byte[] y = makeCrc2bytes(x, oldLen);
    Array.Resize<byte>(ref x, x.Length + y.Length);
    Array.Copy(y, 0, x, oldLen, y.Length);
    return x;
}

... Example ...

byte[] buffer = new byte[6];
    buffer[0] = 0x01;
    buffer[1] = 0x02;
    buffer[2] = 0x03;
    buffer[3] = 0x04;
    buffer[4] = 0x05;
    buffer[5] = 0x06;
 byte[] buffer2 = buffer.AddCrc();  // Now work.
Matthew Whited
  • 22,160
  • 4
  • 52
  • 69
Kazuhiko Nakayama
  • 801
  • 1
  • 8
  • 24
  • Downvoted. I accept all. I learned How to write from Matthew's. In future, I will do well. In stackoverflow, All page is useful. I hope My poor question and great answer from Matthew will help someone : ) – Kazuhiko Nakayama Sep 12 '17 at 00:50

1 Answers1

1

You are having a compiler error since you aren't passing the unused type parameter. Remove that from the .AddCrc(...) method. BTW, the array you passed into .AddCrc() is by value so it is not extended. Array.Resize<T>(...) creates a new array, copies the original value into that array then changes the reference passed into the function (ref).

You may as well do this...

public static byte[] AddCrc(this byte[] input) //type param not used.
{
    if (input == null) throw new ArgumentNullException("input");

    var crc = makeCrc2bytes(input, input.Length);

    var result = new byte[input.Length + crc.Length];
    Array.Copy(input, 0, result, 0, input.Length);
    Array.Copy(crc, 0, result, input.Length, crc.Length);
    return result;
}
Matthew Whited
  • 22,160
  • 4
  • 52
  • 69