---
title: "Slice and reshape tensors in C#"
url: https://recursiveai.org/onemodel/cookbook/slice-and-reshape-tensor-views/
description: "Slice and transpose C# tensors without moving data, inspect strides, and detect when reshaping shares storage or creates a contiguous copy."
version: "1.3.0"
---

# Slice and reshape tensors in C#

**OneModel** is a free, open-source neural-network library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneModel) · [GitHub](https://github.com/recursive-ai-oss/onemodel-csharp) · [Docs](https://recursiveai.org/onemodel/docs/) · [Download example (.zip)](https://recursiveai.org/onemodel/cookbook/slice-and-reshape-tensor-views/slice-and-reshape-tensor-views.zip)

Tensor views share storage; reshaping may need a copy.

```shell
dotnet add package RecursiveAI.OneModel
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneModel.Tensors;
using var x = Tensor.FromSpan<float>(
    [0, 1, 2, 3, 4, 5], Shape.Create(2, 3));
var slice = x.Slice(1, 0, 3, 2);
var transposed = slice.Transpose(0, 1);
using var flat = transposed.Reshape(4);
var values = flat.Data<float>().ToArray();
Console.WriteLine(string.Join(",", values));
```

Prints:

```text
0,3,2,5
```

Unzip [the example](https://recursiveai.org/onemodel/cookbook/slice-and-reshape-tensor-views/slice-and-reshape-tensor-views.zip), then `dotnet run`.

## The full program

The snippet starts with rows `[0, 1, 2]` and `[3, 4, 5]`, keeps columns zero and two, transposes, then flattens. The full program separately inspects the original reshape, a transposed copy and an expanded view.

```csharp
using RecursiveAI.OneModel.Tensors;

using var source = Tensor.FromSpan<float>([0, 1, 2, 3, 4, 5], Shape.Create([2, 3]));
var slice = source.Slice(1, 0, 3, 2);
Console.WriteLine($"slice strides: {slice.Strides}");
Console.WriteLine($"slice [1,1]: {slice.Get<float>(1, 1)}");
Console.WriteLine($"source reshape is view: {source.TryReshape(Shape.Create([6]), out var view)}");
var transposed = source.Transpose(0, 1);
Console.WriteLine($"transpose strides: {transposed.Strides}");
Console.WriteLine($"transpose flatten is view: {transposed.TryReshape(Shape.Create([6]), out _)}");
using var flat = transposed.Reshape(6);
Console.WriteLine($"flat: {string.Join(",", flat.Data<float>().ToArray())}");
var expanded = source.Slice(0, 0, 1).Expand(Shape.Create([2, 3]));
Console.WriteLine($"expand strides: {expanded.Strides}");
view.Set(99f, 0);
Console.WriteLine($"shared source: {source.Get<float>(0, 0)}; copied flat: {flat.Get<float>(0)}");
```

`dotnet run` prints:

```text
slice strides: (3,2)
slice [1,1]: 5
source reshape is view: True
transpose strides: (1,3)
transpose flatten is view: False
flat: 0,3,1,4,2,5
expand strides: (0,1)
shared source: 99; copied flat: 0
```

Invalid shapes throw `TensorShapeException`; accessing any view after its shared storage is released throws `StaleTensorException`.

## Variations

### Reverse element order

`Flip` uses a negative stride; make a contiguous copy before reading it as a flat data span:

```csharp
using RecursiveAI.OneModel.Tensors;
using var x = Tensor.FromSpan<float>([1, 2, 3], Shape.Create(3));
var reversed = x.Flip(0);
using var copy = reversed.Contiguous();
Console.WriteLine(string.Join(",", copy.Data<float>().ToArray()));
```

```text
3,2,1
```

## Related recipes

- [Train a neural network](https://recursiveai.org/onemodel/cookbook/train-a-model/)
- [Run an ONNX model](https://recursiveai.org/onemodel/cookbook/run-onnx-model/)
- [Differentiate a tensor expression](https://recursiveai.org/onemodel/cookbook/differentiate-tensor-expression/)

## The short answer

Use `Slice` to select a range, `Transpose` to swap axes, and `TryReshape` to ask whether a shape change can share storage. `Reshape` succeeds by making a contiguous copy when a view is not possible. Keep the shared source alive until every dependent view is finished.

## What is the difference between tensor reshape and a view?

A view changes shape, strides or offset without moving elements. A reshape requests a new grouping of the same logical elements. In OneModel that request can return a view or allocate a copy. `TryReshape(shape, out view)` distinguishes the viewable case without requesting the fallback copy.

The [tensor reference](https://recursiveai.org/onemodel/docs/tensors/) defines viewability in terms of contiguous runs of dimensions. Neighboring axes can merge when the outer stride equals the inner stride multiplied by the inner extent. A requested shape must regroup those runs without changing their order. Extent-one dimensions receive special treatment, and empty tensors are always viewable.

The example’s original two-by-three tensor is contiguous. Flattening it to six elements therefore succeeds as a view. Transposing first changes the strides to `(1, 3)`; flattening that layout cannot describe its logical sequence with a single stride. `TryReshape` returns false, while `Reshape(6)` copies and produces `0,3,1,4,2,5`.

Do not assume a non-contiguous tensor always needs a copy for every new shape. Some changes only split a compatible run. Ask `TryReshape` for the particular target shape instead of using `IsContiguous` as a universal test.

## How do you transpose a tensor in C#?

Call `Transpose(a, b)` to swap two dimensions. It swaps both shape and stride metadata. It does not reverse the contents of a flat buffer or physically rearrange the stored values. Use `Permute` when you need a general axis permutation rather than one swap.

For the source rows `[0, 1, 2]` and `[3, 4, 5]`, transposition yields logical rows `[0, 3]`, `[1, 4]` and `[2, 5]`. Merely reshaping the source to three-by-two would instead group its row-major sequence as `[0, 1]`, `[2, 3]` and `[4, 5]`. The shape agrees but the axis meaning does not.

`Data<float>()` is for a contiguous logical span. Use indexed `Get<float>` to read a strided view, or call `Contiguous()` and read the returned contiguous tensor. The variation reverses a vector with `Flip`, whose negative stride changes traversal order, then copies it for span access.

## How do tensor slices and expanded views share memory?

`Slice(axis, start, end, step)` uses an exclusive end and a positive step. In the full program, every other column of a two-by-three tensor has strides `(3, 2)`, and the indexed value at `[1, 1]` is five. Slicing adjusts offset and strides; it does not allocate a smaller data buffer.

`Expand` broadcasts extent-one dimensions with stride zero. Both rows of the expanded view therefore reach the same underlying row. Writes through aliases affect shared storage. The full program writes ninety-nine through the flattened source view: the source changes, while the independently copied transposed flatten remains zero at its first element.

Ownership follows storage, not the number of variable names. Disposing a tensor releases its buffer for every view and every copied handle. Do not dispose a temporary view and then continue reading its source. This example disposes the original owner and the independent copied result, leaving shared aliases alone. For `Contiguous`, remember that an already contiguous tensor is returned unchanged; it is not a guaranteed independent copy.
