An open API service indexing awesome lists of open source software.

https://github.com/tyrrrz/polyshim

Collection of polyfills for projects targeting older versions of .NET
https://github.com/tyrrrz/polyshim

backwards-compatibility compat compatibility dotnet dotnet-core dotnet-framework dotnet-standard polyfill shim

Last synced: 3 days ago
JSON representation

Collection of polyfills for projects targeting older versions of .NET

Awesome Lists containing this project

README

          

# PolyShim

[![Status](https://img.shields.io/badge/status-active-47c219.svg)](https://github.com/Tyrrrz/.github/blob/prime/docs/project-status.md)
[![Made in Ukraine](https://img.shields.io/badge/made_in-ukraine-ffd700.svg?labelColor=0057b7)](https://tyrrrz.me/ukraine)
[![Build](https://img.shields.io/github/actions/workflow/status/Tyrrrz/PolyShim/main.yml?branch=prime)](https://github.com/Tyrrrz/PolyShim/actions)
[![Coverage](https://img.shields.io/codecov/c/github/Tyrrrz/PolyShim/prime)](https://codecov.io/gh/Tyrrrz/PolyShim)
[![Version](https://img.shields.io/nuget/v/PolyShim.svg)](https://nuget.org/packages/PolyShim)
[![Downloads](https://img.shields.io/nuget/dt/PolyShim.svg)](https://nuget.org/packages/PolyShim)
[![Discord](https://img.shields.io/discord/869237470565392384?label=discord)](https://discord.gg/2SUWKFnHSm)
[![Fuck Russia](https://img.shields.io/badge/fuck-russia-e4181c.svg?labelColor=000000)](https://twitter.com/tyrrrz/status/1495972128977571848)


Development of this project is entirely funded by the community. Consider donating to support!


Icon

**PolyShim** is a collection of polyfills that enable many modern framework APIs and compiler features for projects targeting older versions of .NET.
It's distributed as a source-only package that can be referenced without imposing any run-time dependencies.

## Terms of use[[?]](https://github.com/Tyrrrz/.github/blob/prime/docs/why-so-political.md)

By using this project or its source code, for any purpose and in any shape or form, you grant your **implicit agreement** to all the following statements:

- You **condemn Russia and its military aggression against Ukraine**
- You **recognize that Russia is an occupant that unlawfully invaded a sovereign state**
- You **support Ukraine's territorial integrity, including its claims over temporarily occupied territories of Crimea and Donbas**
- You **reject false narratives perpetuated by Russian state propaganda**

To learn more about the war and how you can help, [click here](https://tyrrrz.me/ukraine). Glory to Ukraine! πŸ‡ΊπŸ‡¦

## Install

- πŸ“¦ [NuGet](https://nuget.org/packages/PolyShim): `dotnet add package PolyShim`

> [!IMPORTANT]
> To reference this package, you must have the latest major version of the .NET SDK installed.
> This is only required for the build process, and does not affect which version of the runtime you can target.

> [!NOTE]
> Installing this package automatically sets your project's target language version to latest.
> This is required for many polyfills to work, but is also recommended, since **PolyShim** provides the facilities to use modern language features on older frameworks.
> If you have `` explicitly configured in your project file, make sure it's set to `latest` or newer (e.g. `preview`).

## Features

- Enables compiler support for:
- [Nullable reference types](https://learn.microsoft.com/dotnet/csharp/language-reference/builtin-types/nullable-reference-types)
- [Record types](https://learn.microsoft.com/dotnet/csharp/language-reference/builtin-types/record)
- [Init-only properties](https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/init)
- [Required properties](https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/required)
- [Value tuples](https://learn.microsoft.com/dotnet/csharp/language-reference/builtin-types/value-tuples)
- [Index and range operators](https://learn.microsoft.com/dotnet/csharp/language-reference/language-specification/ranges)
- [Caller information](https://learn.microsoft.com/dotnet/csharp/language-reference/attributes/caller-information)
- Module initializers
- Overload priority
- Provides type polyfills for:
- `ValueTuple<...>`
- `Index` and `Range`
- `Span` and `Memory`
- `Lock`
- `HashCode`
- `ArrayPool`
- `TaskCompletionSource`
- [...and 70+ more](Signatures.md)
- Provides member polyfills for:
- `string.ReplaceLineEndings(...)`, `string.AsSpan()`, etc.
- `Stream.ReadExactly(...)`, `Stream.ReadAtLeast(...)`, etc.
- `IEnumerable.Chunk(...)`, `IEnumerable.TakeLast(...)`, etc.
- `Task.WaitAsync(...)`, `Task.WhenEach(...)`, etc.
- `Parallel.ForEachAsync(...)`, `Parallel.ForAsync(...)`, etc.
- `File.WriteAllTextAsync(...)`, `File.ReadAllTextAsync(...)`, etc.
- `Environment.ProcessPath`, `Environment.ProcessId`, etc.
- `OperatingSystem.IsWindows()`, `OperatingSystem.IsLinux()`, etc.
- [...and 250+ more](Signatures.md)
- Adjusts polyfills based on available capabilities
- Targets .NET Standard 1.0+, .NET Core 1.0+, .NET Framework 3.5+
- Imposes no run-time dependencies

## Usage

**PolyShim** polyfills come in two forms:

- **Type polyfills**, which define missing built-in types by reimplementing them from scratch.
- **Member polyfills**, which are provided through global extension members that substitute missing members on existing built-in types.

Once the package is installed, the polyfills will be automatically added to your project as internal source files.
You can then use them in your code by referencing the corresponding types or members as if they were defined natively.

> [!NOTE]
> Polyfills are only applied to types and members that are not already provided.
> When a native implementation of a symbol is available β€” either in the framework or through a referenced [compatibility package](#compatibility-packages) β€” it will always be prioritized over the corresponding polyfill.

### Type polyfills

**PolyShim** provides various types that are not available natively on older target frameworks.
These types are defined within the corresponding `System.*` namespaces and mimic the behavior of their original implementations as closely as possible.

For example, with **PolyShim** you can use the `Index` and `Range` structs (added in .NET Core 3.0) on any version of .NET:

```csharp
using System;

// On newer frameworks, this references the framework-provided types.
// On older frameworks, this references the polyfilled types.
// Same code works everywhere without any changes.
var index = new Index(1, fromEnd: true);
var range = new Range(
new Index(3),
new Index(1, true)
);
```

You can also use compiler features that rely on these types, such as the advanced indexing and slicing operators:

```csharp
var array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// On newer frameworks, these operators rely on the framework-provided types.
// On older frameworks, these operators rely on the polyfilled types.
// Same code works everywhere without any changes.
var last = array[^1];
var part = array[3..^1];
```

> [!NOTE]
> You can find the full list of type polyfills [here](Signatures.md).

### Member polyfills

**PolyShim** provides a number of extension members that act as shims for instance or static members that are not available natively on older target frameworks.
These extension members are defined within the global namespace, so they can be used on the corresponding types just like intrinsic members, without any additional `using` directives.

For example, with **PolyShim** you can reference the `Environment.ProcessId` static property (added in .NET 5.0) on any version of .NET:

```csharp
using System;

// On newer frameworks, this references the framework-provided property.
// On older frameworks, this references the polyfilled (extension) property.
// Same code works everywhere without any changes.
var processId = Environment.ProcessId;
```

> [!NOTE]
> You can find the full list of member polyfills [here](Signatures.md).

### Unsafe code

Certain polyfills that implement low-level memory manipulation features (e.g. `Span.ctor(void*, int)`) require unsafe code to work.
Because **PolyShim** is a source-only package, unsafe code needs to be enabled in your project if you wish to use those polyfills.
To do that, set the `` property to `true`:

```xml


netstandard2.0


true



```

For example, with unsafe code enabled, you can use stack-allocated span initialization on any version of .NET:

```csharp
Span buffer = stackalloc byte[256];
```

### Compatibility packages

Some features from newer versions of .NET can also be made available on older frameworks using official compatibility packages published by Microsoft.
**PolyShim** automatically detects if any of these packages are installed and adjusts its polyfill coverage accordingly β€” either by enabling additional polyfills that build upon those features, or by disabling polyfills for APIs that are already provided in the compatibility packages.

Currently, **PolyShim** recognizes the following packages:

- [`System.Diagnostics.Process`](https://nuget.org/packages/System.Diagnostics.Process) β€” `Process`, `ProcessStartInfo`, etc.
- [`System.Management`](https://nuget.org/packages/System.Management) β€” `ManagementObjectSearcher`, etc.
- [`System.Memory`](https://nuget.org/packages/System.Memory) β€” `Memory`, `Span`, etc.
- [`System.Net.Http`](https://nuget.org/packages/System.Net.Http) β€” `HttpClient`, `HttpContent`, etc.
- [`System.Runtime.InteropServices.RuntimeInformation`](https://nuget.org/packages/System.Runtime.InteropServices.RuntimeInformation) β€” `RuntimeInformation`, `OSPlatform`, etc.
- [`System.Threading.Tasks`](https://nuget.org/packages/System.Threading.Tasks) β€” `Task`, `Task`, etc.
- [`System.Threading.Tasks.Extensions`](https://nuget.org/packages/System.Threading.Tasks.Extensions) β€” `ValueTask`, `ValueTask`, etc.
- [`System.ValueTuple`](https://nuget.org/packages/System.ValueTuple) β€” `ValueTuple<...>`, etc.
- [`Microsoft.Bcl.Async`](https://nuget.org/packages/Microsoft.Bcl.Async) β€” `Task`, `Task`, etc. (wider support than the `System.*` variant).
- [`Microsoft.Bcl.AsyncInterfaces`](https://nuget.org/packages/Microsoft.Bcl.AsyncInterfaces) β€” `IAsyncEnumerable`, `IAsyncDisposable`, etc.
- [`Microsoft.Bcl.HashCode`](https://nuget.org/packages/Microsoft.Bcl.HashCode) β€” `HashCode`, etc.
- [`Microsoft.Bcl.Memory`](https://nuget.org/packages/Microsoft.Bcl.Memory) β€” `Index`, `Range`, etc.
- [`Microsoft.Bcl.TimeProvider`](https://nuget.org/packages/Microsoft.Bcl.TimeProvider) β€” `TimeProvider`, `ITimer`, etc.
- [`Microsoft.Net.Http`](https://nuget.org/packages/Microsoft.Net.Http) β€” `HttpClient`, `HttpContent`, etc. (wider support than the `System.*` variant).

For example, adding a reference to the `Microsoft.Bcl.AsyncInterfaces` package will enable **PolyShim**'s polyfills that work with `IAsyncEnumerable`, such as `Task.WhenEach(...)`:

```xml


netstandard2.0




```

```csharp
using System;
using System.Linq;
using System.Threading.Tasks;

var tasks = Enumerable.Range(1, 10).Select(async i =>
{
await Task.Delay(Random.Shared.Next(1000));
return i * i;
});

// Microsoft.Bcl.AsyncInterfaces is referenced, so this polyfill is enabled
await foreach (var completedTask in Task.WhenEach(tasks))
{
Console.WriteLine(await completedTask);
}
```

Conversely, adding a reference to the `System.Memory` package will disable **PolyShim**'s own versions of `Span` and `Memory`.
You can leverage this to prioritize the official implementation wherever possible, while still benefiting from other polyfills provided by **PolyShim**:

```xml


netstandard2.0




```

```csharp
using System.Buffers;

// System.Memory is referenced, so this polyfill is disabled
// (the official MemoryPool is used instead)
using var buffer = MemoryPool.Shared.Rent(1024);
var memory = buffer.Memory.Slice(0, 1024);
```