Source only package that exposes newer .NET and C# features to older runtimes.
The package targets netstandard2.0
and is designed to support the following runtimes.
net461
,net462
,net47
,net471
,net472
,net48
,net481
netcoreapp2.0
,netcoreapp2.1
,netcoreapp3.0
,netcoreapp3.1
net5.0
,net6.0
,net7.0
,net8.0
,net9.0
API count: 410
See Milestones for release notes.
Some polyfills are implemented in a way that will not have the equivalent performance to the actual implementations.
For example the polyfill for StringBuilder.Append(ReadOnlySpan<char>)
on netcore2 is:
public StringBuilder Append(ReadOnlySpan<char> value)
=> target.Append(value.ToString());
Which will result in a string allocation.
As Polyfill is implemented as a source only nuget, the implementation for each polyfill is compiled into the IL of the resulting assembly. As a side-effect that implementation will continue to be used even if that assembly is executed in a runtime that has a more efficient implementation available.
As a result, in the context of a project producing nuget package, that project should target all frameworks from the lowest TargetFramework up to and including the current framework. This way the most performant implementation will be used for each runtime. Take the following examples:
- If a nuget's minimum target is net6, then the resulting TargetFrameworks should also include net7.0 and net8.0
- If a nuget's minimum target is net471, then the resulting TargetFrameworks should also include net472 and net48"
https://nuget.org/packages/Polyfill/
This project uses features from the current stable SDK and C# language. As such consuming projects should target those:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<LangVersion>latest</LangVersion>
{
"sdk": {
"version": "8.0.301",
"rollForward": "latestFeature"
}
}
The default type visibility for all polyfills is internal
. This means it can be consumed in multiple projects and types will not conflict.
If Polyfill is being consumed in a solution that produce an app, then it is recommended to use the Polyfill nuget only in the root "app project" and enable PolyPublic
.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<PolyPublic>true</PolyPublic>
Then all consuming projects, like tests, will not need to use the Polyfill nuget.
If Polyfill is being consumed in a solution that produce a library (and usually a nuget), then the Polyfill nuget can be added to all projects.
If, however, InternalsVisibleTo
is being used to expose APIs (for example to test projects), then the Polyfill nuget should be added only to the root library project.
Reference: Module Initializers
static bool InitCalled;
[Test]
public void ModuleInitTest() =>
Assert.True(InitCalled);
[ModuleInitializer]
public static void ModuleInit() =>
InitCalled = true;
Reference: init (C# Reference)
class InitSample
{
public int Member { get; init; }
}
- AllowNullAttribute
- DisallowNullAttribute
- DoesNotReturnAttribute
- DoesNotReturnIfAttribute
- MaybeNullAttribute
- MaybeNullWhenAttribute
- MemberNotNullAttribute
- MemberNotNullWhenAttribute
- NotNullAttribute
- NotNullIfNotNullAttribute
- NotNullWhenAttribute
Reference: Nullable reference types
Reference: C# required modifier
public class Person
{
public Person()
{
}
[SetsRequiredMembers]
public Person(string name) =>
Name = name;
public required string Name { get; init; }
}
Indicates that compiler support for a particular feature is required for the location where this attribute is applied.
Can be used to make types compatible with collection expressions
Indicates that the specified method parameter expects a constant.
Reference: SkipLocalsInitAttribute
the SkipLocalsInit attribute prevents the compiler from setting the .locals init flag when emitting to metadata. The SkipLocalsInit attribute is a single-use attribute and can be applied to a method, a property, a class, a struct, an interface, or a module, but not to an assembly. SkipLocalsInit is an alias for SkipLocalsInitAttribute.
class SkipLocalsInitSample
{
[SkipLocalsInit]
static void ReadUninitializedMemory()
{
Span<int> numbers = stackalloc int[120];
for (var i = 0; i < 120; i++)
{
Console.WriteLine(numbers[i]);
}
}
}
Reference: Indices and ranges
If consuming in a project that targets net461 or net462, a reference to System.ValueTuple is required. See References: System.ValueTuple.
[TestFixture]
class IndexRangeSample
{
[Test]
public void Range()
{
var substring = "value"[2..];
Assert.AreEqual("lue", substring);
}
[Test]
public void Index()
{
var ch = "value"[^2];
Assert.AreEqual('u', ch);
}
[Test]
public void ArrayIndex()
{
var array = new[]
{
"value1",
"value2"
};
var value = array[^2];
Assert.AreEqual("value1", value);
}
}
C# introduces a new attribute, System.Runtime.CompilerServices.OverloadResolutionPriority, that can be used by API authors to adjust the relative priority of overloads within a single type as a means of steering API consumers to use specific APIs, even if those APIs would normally be considered ambiguous or otherwise not be chosen by C#'s overload resolution rules. This helps framework and library authors guide API usage as they APIs as they develop new and better patterns.
The OverloadResolutionPriorityAttribute can be used in conjunction with the ObsoleteAttribute. A library author may mark properties, methods, types and other programming elements as obsolete, while leaving them in place for backwards compatibility. Using programming elements marked with the ObsoleteAttribute will result in compiler warnings or errors. However, the type or member is still visible to overload resolution and may be selected over a better overload or cause an ambiguity failure. The OverloadResolutionPriorityAttribute lets library authors fix these problems by lowering the priority of obsolete members when there are better alternatives.
[TestFixture]
public class OverloadResolutionPriorityAttributeTests
{
[Test]
public void Run()
{
int[] arr = [1, 2, 3];
//Prints "Span" because resolution priority is higher
Method(arr);
}
[OverloadResolutionPriority(2)]
static void Method(ReadOnlySpan<int> list) =>
Console.WriteLine("Span");
[OverloadResolutionPriority(1)]
static void Method(int[] list) =>
Console.WriteLine("Array");
}
Reference: Low Level Struct Improvements
using System.Diagnostics.CodeAnalysis;
#pragma warning disable CS0169 // Field is never used
struct UnscopedRefUsage
{
int field1;
[UnscopedRef] ref int Prop1 => ref field1;
}
Reference: CallerArgumentExpression
static class FileUtil
{
public static void FileExists(string path, [CallerArgumentExpression("path")] string argumentName = "")
{
if (!File.Exists(path))
{
throw new ArgumentException($"File not found. Path: {path}", argumentName);
}
}
}
static class FileUtilUsage
{
public static string[] Method(string path)
{
FileUtil.FileExists(path);
return File.ReadAllLines(path);
}
}
- AppendInterpolatedStringHandler
- DefaultInterpolatedStringHandler
- InterpolatedStringHandlerAttribute
- InterpolatedStringHandlerArgumentAttribute
- ISpanFormattable
References: String Interpolation in C# 10 and .NET 6, Write a custom string interpolation handler
Reference: .NET 7 - The StringSyntaxAttribute
- DynamicallyAccessedMembersAttribute
- DynamicDependencyAttribute
- RequiresUnreferencedCodeAttribute
- RequiresDynamicCodeAttribute
- UnconditionalSuppressMessageAttribute
Reference: Prepare .NET libraries for trimming
- ObsoletedOSPlatformAttribute
- SupportedOSPlatformAttribute
- SupportedOSPlatformGuardAttribute
- TargetPlatformAttribute
- UnsupportedOSPlatformAttribute
- UnsupportedOSPlatformGuardAttribute
Reference: Platform compatibility analyzer
StackTraceHiddenAttribute
Reference: C# – Hide a method from the stack trace
Reference: Improvements in native code interop in .NET 5.0
The class Polyfill
includes the following extension methods:
Important
The methods using AppendInterpolatedStringHandler
parameter are not extensions because the compiler prefers to use the overload with string
parameter instead.
bool TryFormat(Span<char>, int)
reference
bool TryFormat(Span<char>, int, ReadOnlySpan<char>, IFormatProvider?)
reference
CancellationTokenRegistration Register(Action<object?, CancellationToken>, object?)
referenceCancellationTokenRegistration UnsafeRegister(Action<object?>, object?)
referenceCancellationTokenRegistration UnsafeRegister(Action<object?, CancellationToken>, object?)
reference
Task CancelAsync()
reference
void Clear<T>()
reference
TValue GetOrAdd<TKey, TValue, TArg>(TKey, Func<TKey, TArg, TValue>, TArg) where TKey : notnull
reference
void Clear<T>()
reference
bool TryFormat(Span<char>, int, ReadOnlySpan<char>, IFormatProvider?)
reference
DateTime AddMicroseconds(double)
referenceint Microsecond()
referenceint Nanosecond()
referencebool TryFormat(Span<char>, int, ReadOnlySpan<char>, IFormatProvider?)
reference
DateTimeOffset AddMicroseconds(double)
referenceint Microsecond()
referenceint Nanosecond()
referencebool TryFormat(Span<char>, int, ReadOnlySpan<char>, IFormatProvider?)
reference
bool TryFormat(Span<char>, int, ReadOnlySpan<char>, IFormatProvider?)
reference
bool Remove<TKey, TValue>(TKey, TValue) where TKey : notnull
referencebool TryAdd<TKey, TValue>(TKey, TValue) where TKey : notnull
reference
bool TryFormat(Span<char>, int, ReadOnlySpan<char>, IFormatProvider?)
reference
NullabilityState GetNullability()
NullabilityInfo GetNullabilityInfo()
bool IsNullable()
NullabilityState GetNullability()
NullabilityInfo GetNullabilityInfo()
bool IsNullable()
bool TryFormat(Span<char>, int, ReadOnlySpan<char>, IFormatProvider?)
reference
bool TryFormat(Span<char>, int, ReadOnlySpan<char>)
reference
bool TryGetValue<T>(T, T)
reference
Task<byte[]> GetByteArrayAsync(string, CancellationToken)
referenceTask<byte[]> GetByteArrayAsync(Uri, CancellationToken)
referenceTask<Stream> GetStreamAsync(string, CancellationToken)
referenceTask<Stream> GetStreamAsync(Uri, CancellationToken)
referenceTask<string> GetStringAsync(string, CancellationToken)
referenceTask<string> GetStringAsync(Uri, CancellationToken)
reference
Task<byte[]> ReadAsByteArrayAsync(CancellationToken)
referenceTask<Stream> ReadAsStreamAsync(CancellationToken)
referenceTask<string> ReadAsStringAsync(CancellationToken)
reference
ReadOnlyDictionary<TKey, TValue> AsReadOnly<TKey, TValue>() where TKey : notnull
reference
IEnumerable<(TFirst First, TSecond Second, TThird Third)> Zip<TFirst, TSecond, TThird>(IEnumerable<TSecond>, IEnumerable<TThird>)
referenceIEnumerable<(TFirst First, TSecond Second)> Zip<TFirst, TSecond>(IEnumerable<TSecond>)
reference
IEnumerable<KeyValuePair<TKey, TAccumulate>> AggregateBy<TSource, TKey, TAccumulate>(Func<TSource, TKey>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>, IEqualityComparer<TKey>?) where TKey : notnull
referenceIEnumerable<KeyValuePair<TKey, TAccumulate>> AggregateBy<TSource, TKey, TAccumulate>(Func<TSource, TKey>, Func<TKey, TAccumulate>, Func<TAccumulate, TSource, TAccumulate>, IEqualityComparer<TKey>?) where TKey : notnull
referenceIEnumerable<TSource> Append<TSource>(TSource)
referenceIEnumerable<TSource[]> Chunk<TSource>(int)
referenceIEnumerable<KeyValuePair<TKey, int>> CountBy<TSource, TKey>(Func<TSource, TKey>, IEqualityComparer<TKey>?) where TKey : notnull
referenceIEnumerable<TSource> DistinctBy<TSource, TKey>(Func<TSource, TKey>)
referenceIEnumerable<TSource> DistinctBy<TSource, TKey>(Func<TSource, TKey>, IEqualityComparer<TKey>)
referenceTSource ElementAt<TSource>(Index)
referenceTSource? ElementAtOrDefault<TSource>(Index)
referenceIEnumerable<TSource> Except<TSource>(TSource)
referenceIEnumerable<TSource> Except<TSource>(TSource, IEqualityComparer<TSource>?)
referenceIEnumerable<TSource> Except<TSource>(IEqualityComparer<TSource>, TSource[])
referenceIEnumerable<TSource> ExceptBy<TSource, TKey>(IEnumerable<TKey>, Func<TSource, TKey>)
referenceIEnumerable<TSource> ExceptBy<TSource, TKey>(IEnumerable<TKey>, Func<TSource, TKey>, IEqualityComparer<TKey>?)
referenceTSource FirstOrDefault<TSource>(Func<TSource, bool>, TSource)
referenceTSource FirstOrDefault<TSource>(TSource)
referenceIEnumerable<(int Index, TSource Item)> Index<TSource>()
referenceTSource LastOrDefault<TSource>(TSource)
referenceTSource LastOrDefault<TSource>(Func<TSource, bool>, TSource)
referenceTSource? Max<TSource>(IComparer<TSource>?)
referenceTSource? MaxBy<TSource, TKey>(Func<TSource, TKey>)
referenceTSource? MaxBy<TSource, TKey>(Func<TSource, TKey>, IComparer<TKey>?)
referenceTSource? Min<TSource>(IComparer<TSource>?)
referenceTSource? MinBy<TSource, TKey>(Func<TSource, TKey>)
referenceTSource? MinBy<TSource, TKey>(Func<TSource, TKey>, IComparer<TKey>?)
referenceTSource SingleOrDefault<TSource>(Func<TSource, bool>, TSource)
referenceTSource SingleOrDefault<TSource>(TSource)
referenceIEnumerable<TSource> SkipLast<TSource>(int)
referenceIEnumerable<TSource> Take<TSource>(Range)
referenceIEnumerable<TSource> TakeLast<TSource>(int)
referenceHashSet<TSource> ToHashSet<TSource>(IEqualityComparer<TSource>?)
referencebool TryGetNonEnumeratedCount<TSource>(int)
reference
ReadOnlyCollection<T> AsReadOnly<T>()
reference
bool TryFormat(Span<char>, int, ReadOnlySpan<char>, IFormatProvider?)
reference
TValue? GetValueOrDefault<TKey, TValue>(TKey) where TKey : notnull
referenceTValue GetValueOrDefault<TKey, TValue>(TKey, TValue) where TKey : notnull
reference
void Deconstruct<TKey, TValue>(TKey, TValue)
reference
void AddRange<T>(ReadOnlySpan<T>)
referencevoid CopyTo<T>(Span<T>)
referencevoid InsertRange<T>(int, ReadOnlySpan<T>)
reference
bool TryFormat(Span<char>, int, ReadOnlySpan<char>, IFormatProvider?)
reference
NullabilityState GetNullability()
NullabilityInfo GetNullabilityInfo()
bool HasSameMetadataDefinitionAs(MemberInfo)
referencebool IsNullable()
NullabilityState GetNullability()
NullabilityInfo GetNullabilityInfo()
bool IsNullable()
Task WaitForExitAsync(CancellationToken)
reference
NullabilityState GetNullability()
NullabilityInfo GetNullabilityInfo()
bool IsNullable()
void NextBytes(Span<byte>)
referencevoid Shuffle<T>(T[])
referencevoid Shuffle<T>(Span<T>)
reference
bool EndsWith(string, StringComparison)
referenceSpanLineEnumerator EnumerateLines()
referencebool SequenceEqual(string)
referencebool StartsWith(string, StringComparison)
reference
bool Contains<T>(T) where T : IEquatable<T>
referencebool EndsWith<T>(T) where T : IEquatable<T>?
referenceSpanSplitEnumerator<T> Split<T>(T) where T : IEquatable<T>
referenceSpanSplitEnumerator<T> Split<T>(ReadOnlySpan<T>) where T : IEquatable<T>
referenceSpanSplitEnumerator<T> SplitAny<T>(ReadOnlySpan<T>) where T : IEquatable<T>
referenceSpanSplitEnumerator<T> SplitAny<T>(SearchValues<T>) where T : IEquatable<T>
referencebool StartsWith<T>(T) where T : IEquatable<T>?
reference
ValueMatchEnumerator EnumerateMatches(ReadOnlySpan<char>)
referenceValueMatchEnumerator EnumerateMatches(ReadOnlySpan<char>, int)
referencebool IsMatch(ReadOnlySpan<char>, int)
referencebool IsMatch(ReadOnlySpan<char>)
reference
bool TryFormat(Span<char>, int, ReadOnlySpan<char>, IFormatProvider?)
reference
bool TryFormat(Span<char>, int, ReadOnlySpan<char>, IFormatProvider?)
reference
bool EndsWith(string)
referenceSpanLineEnumerator EnumerateLines()
referencebool SequenceEqual(string)
referencebool StartsWith(string)
referenceSpan<char> TrimEnd()
referenceSpan<char> TrimStart()
reference
bool Contains<T>(T) where T : IEquatable<T>
reference
Task CopyToAsync(Stream, CancellationToken)
referenceValueTask DisposeAsync()
referenceValueTask<int> ReadAsync(Memory<byte>, CancellationToken)
referenceValueTask WriteAsync(ReadOnlyMemory<byte>, CancellationToken)
reference
bool Contains(string, StringComparison)
referencebool Contains(char)
referencevoid CopyTo(Span<char>)
referencebool EndsWith(char)
referenceint GetHashCode(StringComparison)
referencestring[] Split(char, StringSplitOptions)
referencestring[] Split(char, int, StringSplitOptions)
referencebool StartsWith(char)
referencebool TryCopyTo(Span<char>)
reference
StringBuilder Append(ReadOnlySpan<char>)
referenceStringBuilder Append(AppendInterpolatedStringHandler)
referenceStringBuilder Append(IFormatProvider?, AppendInterpolatedStringHandler)
referenceStringBuilder Append(StringBuilder.AppendInterpolatedStringHandler)
referenceStringBuilder Append(IFormatProvider?, StringBuilder.AppendInterpolatedStringHandler)
referenceStringBuilder AppendJoin(string, string[])
referenceStringBuilder AppendJoin(string, Object[])
referenceStringBuilder AppendJoin(char, string[])
referenceStringBuilder AppendJoin(char, object[])
referenceStringBuilder AppendJoin<T>(char, T[])
referenceStringBuilder AppendJoin<T>(string, T[])
referenceStringBuilder AppendLine(AppendInterpolatedStringHandler)
referenceStringBuilder AppendLine(IFormatProvider?, AppendInterpolatedStringHandler)
referenceStringBuilder AppendLine(StringBuilder.AppendInterpolatedStringHandler)
referenceStringBuilder AppendLine(IFormatProvider?, StringBuilder.AppendInterpolatedStringHandler)
referencevoid CopyTo(int, Span<char>, int)
referencebool Equals(ReadOnlySpan<char>)
referenceChunkEnumerator GetChunks()
referenceStringBuilder Replace(ReadOnlySpan<char>, ReadOnlySpan<char>)
referenceStringBuilder Replace(ReadOnlySpan<char>, ReadOnlySpan<char>, int, int)
reference
Task WaitAsync(CancellationToken)
referenceTask WaitAsync(TimeSpan)
referenceTask WaitAsync(TimeSpan, CancellationToken)
reference
Task<TResult> WaitAsync<TResult>(CancellationToken)
referenceTask<TResult> WaitAsync<TResult>(TimeSpan)
referenceTask<TResult> WaitAsync<TResult>(TimeSpan, CancellationToken)
reference
void SetCanceled<T>(CancellationToken)
reference
ValueTask<int> ReadAsync(Memory<char>, CancellationToken)
referenceTask<string> ReadLineAsync(CancellationToken)
referenceTask<string> ReadToEndAsync(CancellationToken)
reference
Task FlushAsync(CancellationToken)
referencevoid Write(StringBuilder?)
referencevoid Write(ReadOnlySpan<char>)
referenceTask WriteAsync(StringBuilder?, CancellationToken)
referenceValueTask WriteAsync(ReadOnlyMemory<char>, CancellationToken)
referencevoid WriteLine(ReadOnlySpan<char>)
referenceValueTask WriteLineAsync(ReadOnlyMemory<char>, CancellationToken)
reference
bool TryFormat(Span<char>, int, ReadOnlySpan<char>, IFormatProvider?)
reference
int Microseconds()
referenceint Nanoseconds()
referencebool TryFormat(Span<char>, int, ReadOnlySpan<char>, IFormatProvider?)
reference
MethodInfo? GetMethod(string, int, BindingFlags, Type[])
referencebool IsAssignableFrom<T>()
bool IsAssignableTo<T>()
bool IsAssignableTo(Type?)
referencebool IsGenericMethodParameter()
reference
bool TryFormat(Span<char>, int, ReadOnlySpan<char>, IFormatProvider?)
reference
bool TryFormat(Span<char>, int, ReadOnlySpan<char>, IFormatProvider?)
reference
bool TryFormat(Span<char>, int, ReadOnlySpan<char>, IFormatProvider?)
reference
Task SaveAsync(XmlWriter, CancellationToken)
referenceTask SaveAsync(Stream, SaveOptions, CancellationToken)
referenceTask SaveAsync(TextWriter, SaveOptions, CancellationToken)
reference
TEnum[] GetValues<TEnum>() where TEnum : struct, Enum
referencebool IsDefined<TEnum>() where TEnum : struct, Enum
referencestring[] GetNames<TEnum>() where TEnum : struct, Enum
referenceTEnum Parse<TEnum>() where TEnum : struct, Enum
referenceTEnum Parse<TEnum>(bool) where TEnum : struct, Enum
referenceTEnum Parse<TEnum>() where TEnum : struct, Enum
referenceTEnum Parse<TEnum>(bool) where TEnum : struct, Enum
referencebool TryParse<TEnum>(TEnum) where TEnum : struct, Enum
referencebool TryParse<TEnum>(bool, TEnum) where TEnum : struct, Enum
reference
bool IsMatch(string, RegexOptions, TimeSpan)
referencebool IsMatch(string, RegexOptions)
referencebool IsMatch(string)
referenceValueMatchEnumerator EnumerateMatches(string)
referenceValueMatchEnumerator EnumerateMatches(string, RegexOptions, TimeSpan)
referenceValueMatchEnumerator EnumerateMatches(string, RegexOptions)
reference
string Join(string[])
referencestring Join(object[])
referencestring Join(string?[], int, int)
referencestring Join<T>(IEnumerable<T>)
reference
bool TryParse(IFormatProvider?, byte)
referencebool TryParse(IFormatProvider?, byte)
referencebool TryParse(byte)
referencebool TryParse(IFormatProvider?, byte)
referencebool TryParse(NumberStyles, IFormatProvider?, byte)
referencebool TryParse(byte)
referencebool TryParse(NumberStyles, IFormatProvider?, byte)
reference
bool TryParse(IFormatProvider?, Guid)
referencebool TryParseExact(ReadOnlySpan<char>, Guid)
referencebool TryParse(IFormatProvider?, Guid)
referencebool TryParse(Guid)
reference
bool TryParse(IFormatProvider?, DateTime)
referencebool TryParse(IFormatProvider?, DateTime)
referencebool TryParse(DateTime)
referencebool TryParse(IFormatProvider?, DateTimeStyles, DateTime)
referencebool TryParseExact(string, IFormatProvider?, DateTimeStyles, DateTime)
referencebool TryParseExact(ReadOnlySpan<char>, IFormatProvider?, DateTimeStyles, DateTime)
reference
bool TryParse(IFormatProvider?, DateTimeOffset)
referencebool TryParse(IFormatProvider?, DateTimeOffset)
referencebool TryParse(DateTimeOffset)
referencebool TryParse(IFormatProvider?, DateTimeStyles, DateTimeOffset)
referencebool TryParseExact(string, IFormatProvider?, DateTimeStyles, DateTimeOffset)
referencebool TryParseExact(ReadOnlySpan<char>, IFormatProvider?, DateTimeStyles, DateTimeOffset)
reference
bool TryParse(IFormatProvider?, double)
referencebool TryParse(IFormatProvider?, double)
referencebool TryParse(double)
referencebool TryParse(IFormatProvider?, double)
referencebool TryParse(NumberStyles, IFormatProvider?, double)
referencebool TryParse(double)
referencebool TryParse(NumberStyles, IFormatProvider?, double)
reference
bool TryParse(IFormatProvider?, int)
referencebool TryParse(IFormatProvider?, int)
referencebool TryParse(int)
referencebool TryParse(IFormatProvider?, int)
referencebool TryParse(NumberStyles, IFormatProvider?, int)
referencebool TryParse(int)
referencebool TryParse(NumberStyles, IFormatProvider?, int)
reference
bool TryParse(IFormatProvider?, int)
referencebool TryParse(IFormatProvider?, int)
referencebool TryParse(int)
referencebool TryParse(IFormatProvider?, int)
referencebool TryParse(NumberStyles, IFormatProvider?, int)
referencebool TryParse(int)
referencebool TryParse(NumberStyles, IFormatProvider?, int)
reference
bool TryParse(IFormatProvider?, sbyte)
referencebool TryParse(IFormatProvider?, sbyte)
referencebool TryParse(sbyte)
referencebool TryParse(IFormatProvider?, sbyte)
referencebool TryParse(NumberStyles, IFormatProvider?, sbyte)
referencebool TryParse(sbyte)
referencebool TryParse(NumberStyles, IFormatProvider?, sbyte)
reference
bool TryParse(IFormatProvider?, short)
referencebool TryParse(IFormatProvider?, short)
referencebool TryParse(short)
referencebool TryParse(IFormatProvider?, short)
referencebool TryParse(NumberStyles, IFormatProvider?, short)
referencebool TryParse(short)
referencebool TryParse(NumberStyles, IFormatProvider?, short)
reference
bool TryParse(IFormatProvider?, uint)
referencebool TryParse(IFormatProvider?, uint)
referencebool TryParse(uint)
referencebool TryParse(IFormatProvider?, uint)
referencebool TryParse(NumberStyles, IFormatProvider?, uint)
referencebool TryParse(uint)
referencebool TryParse(NumberStyles, IFormatProvider?, uint)
reference
bool TryParse(IFormatProvider?, ulong)
referencebool TryParse(IFormatProvider?, ulong)
referencebool TryParse(ulong)
referencebool TryParse(IFormatProvider?, ulong)
referencebool TryParse(NumberStyles, IFormatProvider?, ulong)
referencebool TryParse(ulong)
referencebool TryParse(NumberStyles, IFormatProvider?, ulong)
reference
bool TryParse(IFormatProvider?, ushort)
referencebool TryParse(IFormatProvider?, ushort)
referencebool TryParse(ushort)
referencebool TryParse(IFormatProvider?, ushort)
referencebool TryParse(NumberStyles, IFormatProvider?, ushort)
referencebool TryParse(ushort)
referencebool TryParse(NumberStyles, IFormatProvider?, ushort)
reference
void FileExists()
void DirectoryExists()
void NotEmpty()
void NotEmpty<T>()
void NotEmpty<T>()
void NotEmpty<T>()
void NotEmpty<T>()
void NotEmpty<T>()
void NotEmpty<T>()
void NotEmpty<T>() where T : IEnumerable
T NotNull<T>() where T : class
string NotNull()
string NotNullOrEmpty()
T NotNullOrEmpty<T>() where T : IEnumerable
Memory<char> NotNullOrEmpty()
ReadOnlyMemory<char> NotNullOrEmpty()
string NotNullOrWhiteSpace()
Memory<char> NotNullOrWhiteSpace()
ReadOnlyMemory<char> NotNullOrWhiteSpace()
void NotWhiteSpace()
void NotWhiteSpace()
void NotWhiteSpace()
void NotWhiteSpace()
void NotWhiteSpace()
void Enter()
bool TryEnter()
bool TryEnter(TimeSpan)
bool TryEnter(int)
void Exit()
Scope EnterScope()
If any of the below reference are not included, the related polyfills will be disabled.
If consuming in a project that targets net461
or net462
, a reference to System.ValueTuple nuget is required.
<PackageReference Include="System.ValueTuple"
Version="4.5.0"
Condition="$(TargetFramework.StartsWith('net46'))" />
If using Span APIs and consuming in a project that targets netstandard
, netframework
, or netcoreapp2*
, a reference to System.Memory nuget is required.
<PackageReference Include="System.Memory"
Version="4.5.5"
Condition="$(TargetFrameworkIdentifier) == '.NETStandard' or
$(TargetFrameworkIdentifier) == '.NETFramework' or
$(TargetFramework.StartsWith('netcoreapp2'))" />
If using ValueTask APIs and consuming in a project that target netframework
, netstandard2
, or netcoreapp2
, a reference to System.Threading.Tasks.Extensions nuget is required.
<PackageReference Include="System.Threading.Tasks.Extensions"
Version="4.5.4"
Condition="$(TargetFramework) == 'netstandard2.0' or
$(TargetFramework) == 'netcoreapp2.0' or
$(TargetFrameworkIdentifier) == '.NETFramework'" />
Given the following class
class NullabilityTarget
{
public string? StringField;
public string?[] ArrayField;
public Dictionary<string, object?> GenericField;
}
[Test]
public void Test()
{
var type = typeof(NullabilityTarget);
var arrayField = type.GetField("ArrayField")!;
var genericField = type.GetField("GenericField")!;
var context = new NullabilityInfoContext();
var arrayInfo = context.Create(arrayField);
Assert.AreEqual(NullabilityState.NotNull, arrayInfo.ReadState);
Assert.AreEqual(NullabilityState.Nullable, arrayInfo.ElementType!.ReadState);
var genericInfo = context.Create(genericField);
Assert.AreEqual(NullabilityState.NotNull, genericInfo.ReadState);
Assert.AreEqual(NullabilityState.NotNull, genericInfo.GenericTypeArguments[0].ReadState);
Assert.AreEqual(NullabilityState.Nullable, genericInfo.GenericTypeArguments[1].ReadState);
}
Enable by adding and MSBuild property PolyNullability
<PropertyGroup>
...
<PolyNullability>true</PolyNullability>
</PropertyGroup>
NullabilityInfoExtensions
provides static and thread safe wrapper around NullabilityInfoContext
. It adds three extension methods to each of ParameterInfo, PropertyInfo, EventInfo, and FieldInfo.
GetNullabilityInfo
: returns theNullabilityInfo
for the target info.GetNullability
: returns theNullabilityState
for the state (NullabilityInfo.ReadState
orNullabilityInfo.WriteState
depending on which has more info) of target info.IsNullable
: given the state (NullabilityInfo.ReadState
orNullabilityInfo.WriteState
depending on which has more info) of the info:- Returns true if state is
NullabilityState.Nullable
. - Returns false if state is
NullabilityState.NotNull
. - Throws an exception if state is
NullabilityState.Unknown
.
- Returns true if state is
Enable by adding and MSBuild property PolyGuard
<PropertyGroup>
...
<PolyGuard>true</PolyGuard>
</PropertyGroup>
Guard
is designed to be a an alternative to the ArgumentException.ThrowIf*
APIs added in net7.
ArgumentException.ThrowIfNullOrEmpty
referenceArgumentException.ThrowIfNullOrWhiteSpace
referenceArgumentNullException.ThrowIfNull
reference
With the equivalent Guard APIs:
Guard.NotNullOrEmpty
Guard.NotNullOrWhiteSpace
Guard.NotNull
Polyfills.Guard
provides the following APIs:
void DirectoryExists(String)
void FileExists(String)
void NotEmpty(String)
void NotEmpty<T>(ReadOnlySpan<T>)
void NotEmpty<T>(Span<T>)
void NotEmpty<T>(Nullable<Memory<T>>)
void NotEmpty<T>(Memory<T>)
void NotEmpty<T>(Nullable<ReadOnlyMemory<T>>)
void NotEmpty<T>(ReadOnlyMemory<T>)
void NotEmpty<T>(T) where T : Collections.IEnumerable
T NotNull<T>(T)
String NotNull(String)
String NotNullOrEmpty(String)
T NotNullOrEmpty<T>(T) where T : Collections.IEnumerable
Memory<Char> NotNullOrEmpty(Nullable<Memory<Char>>)
ReadOnlyMemory<Char> NotNullOrEmpty(Nullable<ReadOnlyMemory<Char>>)
String NotNullOrWhiteSpace(String)
Memory<Char> NotNullOrWhiteSpace(Nullable<Memory<Char>>)
ReadOnlyMemory<Char> NotNullOrWhiteSpace(Nullable<ReadOnlyMemory<Char>>)
void NotWhiteSpace(String)
void NotWhiteSpace(ReadOnlySpan<Char>)
void NotWhiteSpace(Nullable<Memory<Char>>)
void NotWhiteSpace(Nullable<ReadOnlyMemory<Char>>)
void NotWhiteSpace(Span<Char>)
https://github.com/Tyrrrz/PolyShim
https://github.com/Sergio0694/PolySharp
https://github.com/theraot/Theraot
- https://github.com/manuelroemer/Nullable
- https://github.com/bgrainger/IndexRange
- https://github.com/manuelroemer/IsExternalInit
PolySharp uses c# source generators. In my opinion a "source-only package" implementation is better because:
- Simpler implementation
- Easier to debug if something goes wrong.
- Uses less memory at compile time. Since there is no source generator assembly to load.
- Faster at compile time. Since no source generator is required to execute.
The combination of the other 3 packages is not ideal because:
- Required multiple packages to be referenced.
- Does not cover all the scenarios included in this package.
Crack designed by Adrien Coquet from The Noun Project.