1

With C# 8.0 seeing the introduction of the structs Index and Range we can now easily get a slice of an array doing something like

string[] baseArray = {"a","b", "c", "d", "e", "f"};

var arr = baseArray[1..^2];

Does slicing an array like this copy the array? Or does it do it without copying like ArraySegment<T>?

2
  • Your tests aren't really valid. All you're doing it creating the structures, not using them. For example, the Linq version just returns an IEnumerable but doesn't actually do anything. Commented May 24, 2019 at 9:15
  • @DavidG alright, thanks for pointing that out. Removed my test case. However the original question still stands wether or not it copies the array? Commented May 24, 2019 at 9:29

1 Answer 1

4

Try it yourself :

string[] baseArray = { "a", "b", "c", "d", "e", "f" };
var arr = baseArray[1..^2];
Debug.WriteLine(arr[0]);
Debug.WriteLine(baseArray[1]);
arr[0] = "hello";
Debug.WriteLine(arr[0]);
Debug.WriteLine(baseArray[1]);

Output

b
b
hello
b

We can conclude that the string array is copied.

However, if we are using an array of objects :

public class Foo
{
    public string Bar { get; set; }
}

Foo[] baseArray =
{
    new Foo { Bar = "a" },
    new Foo { Bar = "b" },
    new Foo { Bar = "c" },
    new Foo { Bar = "d" },
    new Foo { Bar = "e" },
    new Foo { Bar = "f" }
};

var arr = baseArray[1..^2];
Debug.WriteLine(arr[0].Bar);
Debug.WriteLine(baseArray[1].Bar);
arr[0].Bar = "hello";
Debug.WriteLine(arr[0].Bar);
Debug.WriteLine(baseArray[1].Bar);

arr[0] = new Foo { Bar = "World" };
Debug.WriteLine(arr[0].Bar);
Debug.WriteLine(baseArray[1].Bar);

This outputs

b
b
hello
hello
World
hello

Objects in the array aren't copied but referenced.

Setting another object in an array won't affect the other one.

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

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.