dotnet / dotnet/announcements

Byte Array Interop in .NET 6.0 Preview 6

Open
#187 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
1.4k
Forks
53
PR merge metrics
No merged PRs in 30d

Description

### Summary
Blazor Server & WebAssembly now supports optimized byte array interop which avoids encoding/decoding byte arrays into Base64, facilitating a more efficient interop process.

### Breaking Change
#### Receiving Byte Arrays in JS
```js
function ReceivesByteArray(data)
{
// Previously data was a Base 64 encoded string representing the byte array
// 6.0 Preview 6 and beyond, it'll be a Uint8Array (no longer requires processing the Base 64 encoding)
}
```

which can be invoked by the following C# code:
```csharp
var bytes = new byte[] { 1, 5, 7 };
await _jsRuntime.InvokeVoidAsync("ReceivesByteArray", bytes);
```

#### Sending Byte Arrays from JS
If .NET is expecting a `byte[]` JS must provide a `Uint8Array`. Previously, it was possible to provide a Base64 encoded array using `btoa`.

For example, if you have something like this:
```csharp
var bytes = await _jsRuntime.InvokeAsync("someJSMethodReturningAByteArray");
```

then you _must_ provide a `Uint8Array` from JS (must _not_ be Base 64 encoded).

**Before:**
```js
function someJSMethodReturningAByteArray() {
const data = new Uint8Array([ 1, 2, 3 ]);
const base64EncodedData = btoa(String.fromCharCode.apply(null, data as unknown as number[]));
return base64EncodedData;
}
```

**After:**
```js
function someJSMethodReturningAByteArray() {
const data = new Uint8Array([ 1, 2, 3 ]);
return data;
}
```

PR: https://github.com/dotnet/aspnetcore/pull/33015
Issue: https://github.com/dotnet/aspnetcore/issues/21877

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.