0

I have a byte[] data in which I don't need first element. Array is quiet big, so I don't want to copy it to another array (payload) as shown below.

Buffer.BlockCopy(data, 1, payload, 0, count);

In C++ I can just increment pointer of array to move poiner.

int main()
{
    char* data= "!Hello, World!";
    data++;
    std::cout << data<< std::endl;
}

This part of code prints "Hello, World!". How I can do the same in C#? Maybe to use unsafe code?

4
  • Use a span by slicing the array, data.Slice(1) will create a Span<byte> starting at index 1 of the array and ending at its last element. Commented Mar 25, 2021 at 7:53
  • 2
    You might need to cast the array as a Span<byte> first, I don't know if it's implied. So it should be ((Span<byte>)data).Slice(1);. This will not cause a copy it's essentially a safe pointer to the array. Commented Mar 25, 2021 at 7:57
  • 3
    Modern (C#8) slicing is using [1..]. Commented Mar 25, 2021 at 8:02
  • also, indexing into a Span<T> should be as fast as indexing into an array, if efficiency matters. It is a direct pointer as opposed to ArraySegment<T> which stores a reference to the array and an offset/boundary. Commented Mar 25, 2021 at 8:02

2 Answers 2

2

You can slice arrays in c#8 using [1..].

var data = new char[] {'!','H','e','l','l','o',' ','W','o','r','l','d','!'};
foreach(var ch in data[1..]) Console.Write(ch);
Console.WriteLine();

gives: Hello World!

Sign up to request clarification or add additional context in comments.

Comments

0

Arrays have immutable length, so either start your loops and whatnot from index 1 instead of 0 or copy it to another one

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.