SourceCraftCommunity.SimplifiedCSharp
2.0.0
dotnet add package SourceCraftCommunity.SimplifiedCSharp --version 2.0.0
NuGet\Install-Package SourceCraftCommunity.SimplifiedCSharp -Version 2.0.0
<PackageReference Include="SourceCraftCommunity.SimplifiedCSharp" Version="2.0.0" />
<PackageVersion Include="SourceCraftCommunity.SimplifiedCSharp" Version="2.0.0" />
<PackageReference Include="SourceCraftCommunity.SimplifiedCSharp" />
paket add SourceCraftCommunity.SimplifiedCSharp --version 2.0.0
#r "nuget: SourceCraftCommunity.SimplifiedCSharp, 2.0.0"
#:package SourceCraftCommunity.SimplifiedCSharp@2.0.0
#addin nuget:?package=SourceCraftCommunity.SimplifiedCSharp&version=2.0.0
#tool nuget:?package=SourceCraftCommunity.SimplifiedCSharp&version=2.0.0
Simplified C#
Simplified C# adds frequently used operations directly to existing .NET types through extension methods and provides a small set of practical types for common application tasks. The goal is to make everyday C# shorter without hiding what larger subsystems are being used.
The library targets netstandard2.1 and is intended for modern .NET applications, ASP.NET Core servers, and Unity 6 or newer, including IL2CPP builds.
Highlights
- Compact binary serialization with generated serializers and a reflection fallback.
- JSON serialization backed by
System.Text.Jsonand generated converters. - Fluent collection, string, math, conversion, reflection, random, task, and hashing extensions.
- Deterministic and cryptographically secure implementations of
System.Random. - In-memory and file-backed temporary caches.
- File and folder abstractions.
- Injectable HTTP and WebSocket transports for system and Unity implementations.
- Typed request/response messaging over any
IRemoteConnection. - Localization, local storage, task operations, and lightweight C# code generation.
Modules
| Namespace | Purpose |
|---|---|
FileSystem |
Files, folders, ZIP operations, and persistent temporary caches. |
Http |
HTTP requests, responses, headers, bodies, retries, downloads, and injectable clients. |
Network |
Transport-independent messaging and typed remote requests. |
WebSockets |
Ordered WebSocket messaging with replaceable transports. |
Localization |
Languages, cultures, localized strings, and time formatting. |
LocalData |
Key-value storage and encrypted storage wrappers. |
Logging |
Injectable logger instances used directly or through the global Logs facade. |
Serialization.Binary |
Binary serializer registration and direct serialization. |
Serialization.Generated |
Runtime contracts used by generated serializers. |
CodeGeneration |
Small builders for C# source text. |
Namespace philosophy
The namespace layout is intentional. Fundamental types and extensions are placed in the global namespace or the matching System.* namespace so that installing the package makes them feel like part of the base C# environment. They do not use a SimplifiedCSharp namespace prefix.
Larger optional subsystems use explicit namespaces such as FileSystem, Http, Network, and WebSockets. This keeps module usage visible in source code. Namespace placement by itself is not considered a defect; only a concrete name collision or ambiguous call should be treated as a problem.
Automatic serialization generation
When the source generator is installed as an analyzer, it detects concrete types used by binary and JSON serialization, including calls and method groups routed through generic wrapper methods in this package or application code. Method dependencies are discovered transitively and stored in hidden assembly metadata, so referenced libraries remain analyzable without API-specific generator rules. It emits hidden serializers and registration code automatically; application code continues to call ToBytes, ToJson, storage methods, and the existing read methods without attributes or manual registration. A typeof(...) expression is registered only when it participates in one of these serialization calls.
Generated serializers support compatible public writable fields and public writable auto-properties declared by the serialized type or its base classes. The binary runtime fallback serializes all instance fields from the complete inheritance hierarchy. Unsupported generated shapes use the runtime fallback. Binary serialization is intended for identical contracts and does not provide schema migration.
Generated JSON converters use a direct fast path for JsonOptions.Default and JsonOptions.Indented. Cloned custom options are evaluated at runtime: naming, encoding, member converters, ignore conditions, case-insensitive names, and unmapped-member handling remain generated. Root converters and options that change the complete JSON contract use the standard System.Text.Json converter through a cached options copy without the generated-converter factory.
API reference
The reference lists public members declared by this package. Inherited BCL members are omitted. Each overload is listed separately. A this parameter marks an extension method. Conventional same-type operators are grouped on one line; mixed-type and conversion operators are listed separately.
Core extensions
StringExtensions (global namespace)
string AddTag(this string text, string tag)string Bold(this string text)string? FindFragment(this string text, string startWith, string endWith, StringComparison comparison = StringComparison.Ordinal)— returns the text between two markers.bool IsCorrectCSharpName(this string text)bool IsEmail(this string text)bool IsEnglish(this string text, params char[] addition)bool IsRussian(this string text, params char[] addition)BigInteger ParseToBigInteger(this string text, IFormatProvider? formatProvider = null)decimal ParseToDecimal(this string text, IFormatProvider? formatProvider = null)double ParseToDouble(this string text, IFormatProvider? formatProvider = null)float ParseToFloat(this string text, IFormatProvider? formatProvider = null)int ParseToInt(this string text, IFormatProvider? formatProvider = null)long ParseToLong(this string text, IFormatProvider? formatProvider = null)string Remove(this string text, string fragment)string RemoveLines(this string text, Predicate<string> predicate)string ReplaceFirst(this string text, string oldValue, string newValue, StringComparison comparison = StringComparison.Ordinal)string ReplaceFirst(this string text, string startMark, string endMark, string newValue, StringComparison comparison = StringComparison.Ordinal)— replaces the first marked range.string ReplaceLast(this string text, string oldValue, string newValue, StringComparison comparison = StringComparison.Ordinal)string ReplacePathSeparators(this string path)int RowsCount(this string text)string[] Split(this string text, params string[] separators)string ToCorrectCSharpName(this string text)string ToEscapeDataString(this string text)string ToUnescapeDataString(this string text)
CollectionExtensions (global namespace)
void Add<T>(this ICollection<T> collection, IEnumerable<T> sequence)void AddIfNotContains<T>(this ICollection<T> collection, T item)void AddIfNotContains<T>(this ICollection<T> collection, T item, Func<T, bool> when)void AddOrShift<T>(this IList<T> list, T item, int maxCount)— appends when there is space; otherwise shifts the full collection and writes the new item at the end without shrinking an already larger collection.int AddWithRandomKey<TValue>(this IDictionary<int, TValue> dictionary, TValue value, int maxAttempts = 10_000)— throws when no unique key is generated within the attempt limit.string AddWithRandomKey<TValue>(this IDictionary<string, TValue> dictionary, TValue value, int stringLength, int maxAttempts = 10_000)— throws when no unique key is generated within the attempt limit.T? BinarySearch<T>(this IList<T> source, int target, Func<T, int> selector)— expects values ordered by the selected integer.IEnumerable<T> ByIndex<T>(this IReadOnlyList<T> sequence)void ClearDuplicates<T>(this ICollection<T> collection)bool Contains<T>(this IEnumerable<T> sequence, Func<T, bool> condition)bool Contains<T>(this IEnumerable<T> sequence, Func<T, bool> condition, out T? value)— returnstruewhen a matching item is found, includingnull.bool Contains<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, out TValue value)— returnstruewhen the key exists, including when its value isnull.TValue GetOrAdd<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key, Func<TValue> createFunc)TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TValue> createFunc)void InsertFirst<T>(this IList<T> list, T item)T RandomElement<T>(this IEnumerable<T> sequence, Random? random = null)T RandomElement<T>(this IEnumerable<T> sequence, Func<T, Percent> probabilitySelector, Random? random = null)— selects by non-negative relative weights.IEnumerable<T> RemoveAll<T>(this ICollection<T> collection, Func<T, bool> predicate)— returns the removed items.T RemoveByIndex<T>(this IList<T> list, int index)— removes and returns the item at the exact index.T RemoveFirst<T>(this ICollection<T> collection)T RemoveItem<T>(this ICollection<T> collection, T item)T RemoveLast<T>(this ICollection<T> collection)T RemoveRandom<T>(this ICollection<T> collection)void Shuffle<T>(this IList<T> list, Random? random = null)IEnumerable<T> Shuffled<T>(this IEnumerable<T> sequence, Random? random = null)void SortBy<T, TProperty>(this List<T> list, Func<T, TProperty> selector)void SortByDescending<T, TProperty>(this List<T> list, Func<T, TProperty> selector)IEnumerable<IEnumerable<T>> SplitByGroups<T>(this IEnumerable<T> source, int maxCountInGroup)T TakeOrCreate<T>(this ConcurrentBag<T> bag) where T : new()T TakeOrCreate<T>(this ConcurrentBag<T> bag, Func<T> createFunc)bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key)
ConvertExtensions (global namespace)
T? CastTo<T>(this object? value)TimeSpan Days(this int value)TimeSpan Days(this float value)TimeSpan Days(this double value)TimeSpan Hours(this int value)TimeSpan Hours(this float value)TimeSpan Hours(this double value)TimeSpan Milliseconds(this int value)TimeSpan Milliseconds(this float value)TimeSpan Milliseconds(this double value)TimeSpan Minutes(this int value)TimeSpan Minutes(this float value)TimeSpan Minutes(this double value)TimeSpan Seconds(this int value)TimeSpan Seconds(this float value)TimeSpan Seconds(this double value)DataSize Size(this byte[] bytes)DataSize Size(this string text, Encoding encoding)byte[] ToBase64Bytes(this string text)string ToBase64String(this byte[] bytes)byte[] ToBytes(this string text, Encoding encoding)TEnum ToEnum<TEnum>(this string value) where TEnum : struct, EnumTEnum ToEnumFlags<TEnum>(this IEnumerable<string> sequence) where TEnum : struct, Enumstring ToHexString(this byte[] bytes)int ToInt(this Enum value)string ToMessageWithInnerExceptions(this Exception exception)string ToString(this byte[] bytes, Encoding encoding)string ToStringDebug<T>(this T value, bool typeInfo = false)string ToStringEnumerable<T>(this IEnumerable<T> sequence, Func<T, string>? toString = null, bool typesInfo = false)string ToStringEnumerableNewLine<T>(this IEnumerable<T> sequence, Func<T, string>? toString = null, bool typesInfo = false)Version WithRemovedLastZeros(this Version version)
MathExtensions (global namespace)
int Abs(this int value)long Abs(this long value)float Abs(this float value)double Abs(this double value)decimal Abs(this decimal value)float Acos(this float value)double Acos(this double value)float Acosh(this float value)double Acosh(this double value)float Asin(this float value)double Asin(this double value)float Asinh(this float value)double Asinh(this double value)float Atan(this float value)double Atan(this double value)float Atanh(this float value)double Atanh(this double value)float Cbrt(this float value)double Cbrt(this double value)string Clamp(this string text, int maxLength)— truncates tomaxLength; a negative limit is invalid.DateTime Clamp(this DateTime current, DateTime min, DateTime max)TimeSpan Clamp(this TimeSpan current, TimeSpan min, TimeSpan max)int Clamp(this int current, int min, int max)long Clamp(this long current, long min, long max)float Clamp(this float current, float min, float max)double Clamp(this double current, double min, double max)decimal Clamp(this decimal current, decimal min, decimal max)float Cos(this float value)double Cos(this double value)float Exp(this float value)double Exp(this double value)float Log(this float value)double Log(this double value)float Log(this float value, float newBase)double Log(this double value, double newBase)float Log10(this float value)double Log10(this double value)Percent MoreThan(this long value, long compared)— throws whencomparedis zero.Percent MoreThan(this double value, double compared)— throws whencomparedis zero.Percent MoreThan(this TimeSpan value, TimeSpan compared)— throws whencomparedis zero.Percent MoreThan(this DataSize value, DataSize compared)— throws whencomparedis zero.float Pow(this float value, float power)double Pow(this double value, double power)int Round(this float value)long Round(this double value)long Round(this decimal value)int RoundCeiling(this float value)long RoundCeiling(this double value)long RoundCeiling(this decimal value)int RoundFloor(this float value)long RoundFloor(this double value)long RoundFloor(this decimal value)int Sign(this int value)long Sign(this long value)float Sign(this float value)double Sign(this double value)decimal Sign(this decimal value)float Sin(this float value)double Sin(this double value)float Sqrt(this float value)double Sqrt(this double value)float Tan(this float value)double Tan(this double value)float Tanh(this float value)double Tanh(this double value)int UpdateAverage(this int value, int newValue, int updateCount)long UpdateAverage(this long value, long newValue, long updateCount)float UpdateAverage(this float value, float newValue, int updateCount)double UpdateAverage(this double value, double newValue, long updateCount)decimal UpdateAverage(this decimal value, decimal newValue, long updateCount)TimeSpan UpdateAverage(this TimeSpan value, TimeSpan newValue, long updateCount)DataSize UpdateAverage(this DataSize value, DataSize newValue, long updateCount)
Round, RoundFloor, and RoundCeiling reject non-finite floating-point values and results outside the target integer range. UpdateAverage requires a non-negative previous update count and avoids overflowing an intermediate weighted sum.
LangExtensions (global namespace)
IDisposable AddCloneOverride(CloneOverrideFunc cloneOverrideFunc)— registers a custom clone strategy until disposed.T? Clone<T>(this T value)— usesICloneable, registered overrides, or binary cloning.bool IsEmpty<T>(this T value)bool NotEmpty<T>(this T value)IDisposable ObserveChanges<TSource, TProperty>(this TSource value, Func<TSource, TProperty?> propertySelector, Action<TProperty?> onChanged, CancellationToken cancelToken) where TSource : class— polls through the globalRepeat.Instanceand invokes only after a real change.bool TryDispose<T>(this T value) where T : IDisposableT With<T>(this T value, Action<T> action) where T : classT With<T>(this T value, Action<T> action, Func<bool> when) where T : classT With<T>(this T value, Action<T> action, bool when) where T : classT With<T>(this T value, RefAction<T> action) where T : structT With<T>(this T value, RefAction<T> action, Func<bool> when) where T : structT With<T>(this T value, RefAction<T> action, bool when) where T : struct
LangExtensions.CloneOverrideFunc (global namespace)
delegate bool CloneOverrideFunc(object value, out object clone)
LangExtensions.RefAction<T> (global namespace)
delegate void RefAction<T>(ref T value) where T : struct
HashExtensions (global namespace)
byte[] ComputeHash(this byte[] bytes, HashAlgorithm algorithm)string ComputeHash(this string text, HashAlgorithm algorithm)string ComputeHash(this Stream stream, HashAlgorithm algorithm)string ComputeHash(this FileSystem.File file, HashAlgorithm algorithm)string ComputeHash(this FileSystem.Folder folder, HashAlgorithm algorithm)byte[] ComputeHashBytes(this Stream stream, HashAlgorithm algorithm)byte[] ComputeHashBytes(this FileSystem.File file, HashAlgorithm algorithm)byte[] ComputeHashBytes(this FileSystem.Folder folder, HashAlgorithm algorithm)int ComputeHash32(this byte[] bytes)— deterministicXxHash32with a fixed seed.int ComputeHash32<T>(this T value)— hashes canonical bytes for standard values and binary serialization for custom values; concrete custom types participate in source generation.
TaskExtensions (global namespace)
Task AfterCompletionContinueWith(this Task task, Action action)Task<T?> InvokeAsTask<T>(this Func<T> func)void OnComplete(this Task task, Action action, TaskStatus status = TaskStatus.RanToCompletion)— invokes the callback when the task finishes with the selected status and logs callback failures.void WaitInBackground(this Task task, Action<Exception>? onException = null)void WaitInBackground(this TaskOperation task, Action<Exception>? onException = null)void WaitInBackground(this ValueTask task, Action<Exception>? onException = null)void WaitInBackground<T>(this ValueTask<T> task, Action<Exception>? onException = null)Task<IEnumerable<T>> WhenAll<T>(this IEnumerable<Task<T>> tasks)CancellationTokenSource With(this CancellationTokenSource tokenSource, CancellationToken token)— creates a new linked source; dispose the returned source after use.
JsonExtensions (global namespace)
void Add(this JsonObject json, string propertyName, object value)— serializes the value with the shared JSON options.void AddFirst<T>(this JsonObject json, string propertyName, T value)— serializes with the shared options, preserves existing node instances, and rejects duplicate names without changing the object.string AddJsonIndent(this string json)bool Contains(this JsonObject json, string propertyName)bool Contains<T>(this JsonObject json, string propertyName, out T? value)T? GetProperty<T>(this JsonObject json, string propertyName)T? ReadJson<T>(this Stream stream)object? ReadJson(this Stream stream, Type type)ValueTask<T?> ReadJsonAsync<T>(this Stream stream)ValueTask<object?> ReadJsonAsync(this Stream stream, Type type)string RemoveJsonIndent(this string json)void SetProperty<T>(this JsonObject json, string name, T value)— serializes any supported value into a JSON node.string ToJson<T>(this T value)string ToJson<T>(this T value, Action<JsonSerializerOptions> options)JsonObject? ToJsonObject(this string json)JsonObject? ToJsonObject<T>(this T value)string ToJsonWithIndent<T>(this T value)T? ToObject<T>(this JsonObject json)object? ToObject(this JsonObject json, Type objectType)T? ToObjectFromJson<T>(this string json)T? ToObjectFromJson<T>(this string json, Action<JsonSerializerOptions> options)void WriteJson<T>(this Stream stream, T value)void WriteJson(this Stream stream, object value, Type type)Task WriteJsonAsync<T>(this Stream stream, T value)Task WriteJsonAsync(this Stream stream, object value, Type type)
BinaryExtensions (global namespace)
const string MediaTypeName = "application/bin"const int ApproximateObjectSize = 128ArraySegment<byte> AsBytesRef(this MemoryStream stream)— exposes the written segment without copying.bool BinaryCompare(this object? original, object? other, int approximateSize = 128)bool BinaryCompare(this object? original, object? other, MemoryStream firstStream, MemoryStream secondStream)void Clear(this MemoryStream stream)T? ReadObject<T>(this Stream stream)object? ReadObject(this Stream stream, Type type)Task<object?> ReadObjectAsync(this Stream stream, Type type, int approximateSize = 128)byte[] ToBytes<T>(this T value, int approximateSize = 128)byte[] ToBytes(this object? value, Type type, int approximateSize = 128)T? ToObject<T>(this byte[] bytes, int approximateSize = 128)T? ToObject<T>(this ArraySegment<byte> bytes, int approximateSize = 128)object? ToObject(this byte[] bytes, Type type, int approximateSize = 128)BinarySerializer.ReadConverter ToUniversal<T>(this BinarySerializer.ReadConverter<T> converter)BinarySerializer.WriteConverter ToUniversal<T>(this BinarySerializer.WriteConverter<T> converter)void WriteObject<T>(this Stream stream, T? value)void WriteObject(this Stream stream, object? value, Type? type)Task WriteObjectAsync<T>(this Stream stream, T? value)Task WriteObjectAsync(this Stream stream, object? value, Type type, int approximateSize = 128)
SerializationExtensions (global namespace)
Primitive, platform, file-system, and JSON-token converters used by the binary and JSON serializers.
Binary DateTime values pack ticks and DateTimeKind into one long. JSON uses yyyy-MM-ddTHH:mm:ss.fffffff with |Utc or |Local; no postfix means Unspecified. The format preserves ticks and kind without time-zone conversion.
Large strings, byte arrays, and general arrays are read incrementally. Their final contiguous value is allocated only after the declared content has been read successfully.
bool ReadBoolean(this Stream stream)byte ReadByte(this Stream stream)sbyte ReadSByte(this Stream stream)char ReadChar(this Stream stream)short ReadShort(this Stream stream)ushort ReadUShort(this Stream stream)int ReadInt(this Stream stream)uint ReadUInt(this Stream stream)long ReadLong(this Stream stream)ulong ReadULong(this Stream stream)float ReadFloat(this Stream stream)double ReadDouble(this Stream stream)decimal ReadDecimal(this Stream stream)string? ReadString(this Stream stream)byte[]? ReadByteArray(this Stream stream)Guid ReadGuid(this Stream stream)BigInteger ReadBigInteger(this Stream stream)BigInteger ReadBigInteger(this ref Utf8JsonReader reader)DateTime ReadDateTime(this Stream stream)DateTime ReadDateTime(this ref Utf8JsonReader reader)TimeSpan ReadTimeSpan(this Stream stream)TimeSpan ReadTimeSpan(this ref Utf8JsonReader reader)DataSize ReadDataSize(this Stream stream)DataSize ReadDataSize(this ref Utf8JsonReader reader)Percent ReadPercent(this Stream stream)Percent ReadPercent(this ref Utf8JsonReader reader)IPAddress? ReadIPAddress(this Stream stream)IPAddress? ReadIPAddress(this ref Utf8JsonReader reader)Uri? ReadUri(this Stream stream)Uri? ReadUri(this ref Utf8JsonReader reader)Type? ReadType(this Stream stream)Type? ReadType(this ref Utf8JsonReader reader)FileSystem.File? ReadFile(this Stream stream)FileSystem.File? ReadFile(this ref Utf8JsonReader reader)FileSystem.Folder? ReadFolder(this Stream stream)FileSystem.Folder? ReadFolder(this ref Utf8JsonReader reader)void Write(this Stream stream, bool value)void Write(this Stream stream, byte value)void Write(this Stream stream, sbyte value)void Write(this Stream stream, char value)void Write(this Stream stream, short value)void Write(this Stream stream, ushort value)void Write(this Stream stream, int value)void Write(this Stream stream, uint value)void Write(this Stream stream, long value)void Write(this Stream stream, ulong value)void Write(this Stream stream, float value)void Write(this Stream stream, double value)void Write(this Stream stream, decimal value)void Write(this Stream stream, string? value)void WriteByteArray(this Stream stream, byte[]? value)void Write(this Stream stream, Guid value)void Write(this Stream stream, BigInteger value)void Write(this Utf8JsonWriter writer, BigInteger value)void Write(this Stream stream, DateTime value)void Write(this Utf8JsonWriter writer, DateTime value)void Write(this Stream stream, TimeSpan value)void Write(this Utf8JsonWriter writer, TimeSpan value)void Write(this Stream stream, DataSize value)void Write(this Utf8JsonWriter writer, DataSize value)void Write(this Stream stream, Percent value)void Write(this Utf8JsonWriter writer, Percent value)void Write(this Stream stream, IPAddress? value)void Write(this Utf8JsonWriter writer, IPAddress value)void Write(this Stream stream, Uri? value)void Write(this Utf8JsonWriter writer, Uri? value)void Write(this Stream stream, Type? value)void Write(this Utf8JsonWriter writer, Type? value)void Write(this Stream stream, FileSystem.File? value)void Write(this Utf8JsonWriter writer, FileSystem.File value)void Write(this Stream stream, FileSystem.Folder? value)void Write(this Utf8JsonWriter writer, FileSystem.Folder value)
Logging
Logs (global namespace)
Logging.ILogger Logger { get; set; }event Action<Logs.Type, string>? Receivedvoid AddMessage(string description)void AddMessage(object? value)void AddMessage(string tag, string description)void AddMessage(string tag, object? value)void AddWarning(string description)void AddWarning(object? value)void AddWarning(string tag, string description)void AddWarning(string tag, object? value)void AddError(string description)void AddError(object? value)void AddError(string tag, string description)void AddError(string tag, object? value)
Received forwards events from the current Logger and remains subscribed when the logger is replaced. Subscribers are invoked independently, so one failing subscriber does not interrupt logging or later subscribers.
ILogger (Logging)
event Action<Logs.Type, string>? Receivedvoid Add(Logs.Type type, string description)— implementations handle the entry and then raiseReceived.void AddMessage(string description)void AddMessage(object? value)void AddMessage(string tag, string description)void AddMessage(string tag, object? value)void AddWarning(string description)void AddWarning(object? value)void AddWarning(string tag, string description)void AddWarning(string tag, object? value)void AddError(string description)void AddError(object? value)void AddError(string tag, string description)void AddError(string tag, object? value)
Logs.Type (global namespace)
- Values:
Message,Warning,Error
Core utility types
StringConstants (global namespace)
const string Null = "Null"const string Tab = "\t"const string Space = " "const string Space4 = " "const string EnglishAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"const string Digits = "0123456789"const string EnglishLettersAndDigits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"string NewLine { get; }
DataSize (System)
Represents a byte count. Unknown uses -1. Bit-based units use decimal SI factors; byte-based units use binary factors. Floating-point factories and arithmetic reject non-finite values and overflow; integral arithmetic also throws instead of wrapping.
DataSize(long bytesCount)DataSize Zero { get; }DataSize Unknown { get; }long Count { get; }double TotalBits { get; }double TotalBytes { get; }double TotalKilobits { get; }double TotalKilobytes { get; }double TotalMegabits { get; }double TotalMegabytes { get; }double TotalGigabits { get; }double TotalGigabytes { get; }double TotalTerabits { get; }double TotalTerabytes { get; }double TotalPetabits { get; }double TotalPetabytes { get; }DataSize FromBits(long bits)DataSize FromBytes(long bytes)DataSize FromBytes(double bytes)DataSize FromBytes(byte[] bytes)DataSize FromKilobits(double kilobits)DataSize FromKilobytes(double kilobytes)DataSize FromMegabits(double megabits)DataSize FromMegabytes(double megabytes)DataSize FromGigabits(double gigabits)DataSize FromGigabytes(double gigabytes)DataSize FromTerabits(double terabits)DataSize FromTerabytes(double terabytes)DataSize FromPetabits(double petabits)DataSize FromPetabytes(double petabytes)DataSize Clone()bool Equals(DataSize other)bool Equals(object obj)int GetHashCode()string ToString()implicit operator DataSize(long bytesCount)- Same-type operators:
+,-,*,/,==,!=,>,<,>=,<=. DataSize operator *(DataSize a, int b)DataSize operator *(DataSize a, long b)DataSize operator *(DataSize a, float b)DataSize operator *(DataSize a, double b)DataSize operator /(DataSize a, int b)DataSize operator /(DataSize a, long b)DataSize operator /(DataSize a, float b)DataSize operator /(DataSize a, double b)
Floating-point division rejects zero, non-finite divisors, and results outside the long range.
Percent (System)
Percent(double value)double Valuefloat Float01 { get; }double Double01 { get; }bool Equals(Percent other)bool Equals(object obj)int GetHashCode()string ToString()string ToStringRound()implicit operator Percent(int value)implicit operator Percent(long value)implicit operator Percent(float value)implicit operator Percent(double value)- Same-type operators:
+,-,*,/,==,!=,>,<,>=,<=. Percent operator *(Percent a, int b)Percent operator *(Percent a, float b)Percent operator /(Percent a, int b)Percent operator /(Percent a, float b)
Division rejects zero divisors with DivideByZeroException.
DeterministicRandom (System)
Inherits System.Random and reproduces the same sequence for the same seed across supported runtimes.
DeterministicRandom(int seed)int Seed { get; }void Reset()void Reset(int seed)int Next()int Next(int maxValue)int Next(int minValue, int maxValue)double NextDouble()void NextBytes(byte[] buffer)void NextBytes(Span<byte> buffer)
SecureRandom (System)
Inherits System.Random and uses RandomNumberGenerator.
SecureRandom()SecureRandom Sharedint Next()int Next(int maxValue)int Next(int minValue, int maxValue)double NextDouble()void NextBytes(byte[] buffer)void NextBytes(Span<byte> buffer)
RandomExtensions (System)
bool Bool(this Random random)bool BoolTrue(this Random random, Percent probability)float Float01(this Random random)double Double01(this Random random)int IntMinMax(this Random random)int IntZeroMax(this Random random)int IntMinMaxNoZero(this Random random)float FloatMinMax(this Random random)int Index(this Random random, int count)int Int(this Random random, int minInclusive, int maxInclusive)long Long(this Random random, long minInclusive, long maxInclusive)BigInteger BigInteger(this Random random, BigInteger minInclusive, BigInteger maxInclusive)float Float(this Random random, float minInclusive, float maxExclusive)double Double(this Random random, double minInclusive, double maxExclusive)TEnum Enum<TEnum>(this Random random) where TEnum : struct, Enumstring String(this Random random, int length, char[] characters)string String(this Random random, int length, string characters)Guid CreateGuid(this Random random)
SerializationAlgorithm (System)
- Values:
Binary,Json
ICloneable<T> (System)
T Clone()
IKeyValueStorage (System)
void Set<T>(string key, T value)T Get<T>(string key)T Get<T>(string key, Func<T> defaultValue)bool Contains(string key)bool Contains<T>(string key, out T? value)void Remove(string key)
IMessage<TEnum> (System)
Constraint: TEnum : struct, Enum.
T? ReadAs<T>()
RemoteDisposable (System)
RemoteDisposable(Action disposeFunc)void Dispose()— invokes the action at most once, including concurrent calls.
UniqueAttribute (System)
UniqueAttribute()
ReflectionExtensions (System.Reflection)
IEnumerable<Type> Types { get; }bool ContainsAttribute<TAttribute>(this MemberInfo member) where TAttribute : Attributebool ContainsAttribute(this MemberInfo member, Type attribute)bool ContainsAttribute<TAttribute>(this MemberInfo member, out TAttribute? attribute) where TAttribute : Attributebool ContainsAttribute(this MemberInfo member, Type attributeType, out object? attribute)void CopyFields(this Type type, object original, object to)object? GetDefaultValue(this Type type)TEnum[] GetEnumValues<TEnum>() where TEnum : struct, Enumstring[] GetEnumValuesName<TEnum>() where TEnum : struct, EnumType[] GetLoadableTypes(this Assembly assembly)Type GetMemberType(this MemberInfo member)TValue? GetMemberValue<TValue>(this object source, string name)object? GetMemberValue(this object source, string name)IEnumerable<MemberInfo> GetPublicMembers(this Type type)MethodInfo[] GetStaticMethodsWithAttributes<TAttribute>() where TAttribute : AttributeTask<MethodInfo[]> GetStaticMethodsWithAttributesAsync<TAttribute>(CancellationToken cancellationToken = default) where TAttribute : AttributeIEnumerable<Type> GetSubclasses(this Type type)object? GetValueFromInstance(this MemberInfo member, object instance)bool ImplementsInterface<TInterface>(this Type type)bool ImplementsInterface(this Type type, Type interfaceType)bool InheritedFrom<T>(this Type type)bool InheritedFrom(this Type type, Type baseType)object? InvokeMethod(this object source, string name, params object?[] args)object? InvokeMethod<T1>(this object source, string name, params object?[] args)object? InvokeMethod<T1, T2>(this object source, string name, params object?[] args)object? InvokeMethod<T1, T2, T3>(this object source, string name, params object?[] args)object? InvokeMethod<T1, T2, T3, T4>(this object source, string name, params object?[] args)bool IsDelegate(this Type type)bool IsReferenceType(this Type type)T NewInstance<T>()object NewInstance(this Type type)void SetMemberValue(this object source, string name, object? value)void SetValueOnInstance(this MemberInfo member, object instance, object? value)
SecurityExtensions (System.Security.Cryptography)
string EncryptAES(this string text, string password)string DecryptAES(this string text, string password)bool EqualsFixedTime(this byte[] left, byte[] right)bool EqualsFixedTime(this string left, string right)
JsonOptions (System.Text.Json)
The shared options are read-only. JSON extension overloads that accept Action<JsonSerializerOptions> create a mutable copy before applying changes.
JsonSerializerOptions DefaultJsonSerializerOptions Indented
Collections (System.Collections.Generic)
FixedCache<TKey, TValue> (System.Collections.Generic)
Fixed-size LRU cache. Reading a value updates its recency.
Constraint: TKey : notnull.
FixedCache(int capacity)int Capacity { get; set; }int Count { get; }event Action<TKey, TValue>? ItemRemoved— subscribers run independently; one failure does not prevent later subscribers.void AddOrUpdate(TKey key, TValue value)void Clear()bool ContainsKey(TKey key)IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()bool Remove(TKey key)bool TryGetValue(TKey key, out TValue? value)
ITempCache<TKey, TValue> (System.Collections.Generic)
Constraint: TKey : notnull.
void Clear()bool Contains(TKey key)bool Contains(TKey key, out TValue? value)TValue Get(TKey key)TValue GetOrCreate(TKey key, Func<TValue> factory, TimeSpan? lifetime)void Remove(TKey key)void Set(TKey key, TValue value, TimeSpan? lifetime)bool TryAdd(TKey key, TValue value, TimeSpan? lifetime)
TempCache<TKey, TValue> (System.Collections.Generic)
Thread-safe in-memory cache with optional entry lifetimes.
Constraint: TKey : notnull.
TempCache()void Clear()bool Contains(TKey key)bool Contains(TKey key, out TValue? value)bool Contains(Func<TValue, bool> predicate)void Dispose()TValue? Find(Func<TValue, bool> predicate)TValue Get(TKey key)TValue GetOrCreate(TKey key, Func<TValue> factory, TimeSpan? lifetime)void Remove(TKey key)void Set(TKey key, TValue value, TimeSpan? lifetime)bool TryAdd(TKey key, TValue value, TimeSpan? lifetime)IEnumerable<TValue> Where(Func<TValue, bool> predicate)
TempCacheExtensions (System.Collections.Generic)
TKey AddWithRandomKey<TKey, TValue>(this ITempCache<TKey, TValue> cache, Func<TKey> keyFactory, TValue value, TimeSpan? lifetime = null, int maxAttempts = 10_000, CancellationToken cancellationToken = default) where TKey : notnull— throws when no unique key is generated within the attempt limit.
Tasks (System.Threading.Tasks)
Repeat (System.Threading.Tasks)
Single application-wide scheduler. Replace Instance at application startup to use a platform implementation such as a Unity frame scheduler.
Repeat Instance { get; set; }bool Enabled { get; }IDisposable Action(Action action, CancellationToken token = default)void Dispose()
SystemRepeat (System.Threading.Tasks)
SystemRepeat(int frameRate)
TaskManager (System.Threading.Tasks)
Task Run(Action action)Task Run(Action action, CancellationToken token)Task Run(Action action, TaskCreationOptions options)Task Run(Func<Task> task)Task Run(Func<Task> task, CancellationToken token)Task Run(Func<Task> task, TaskCreationOptions options)Task<T> Run<T>(Func<Task<T>> task)Task RunInBackground(Func<Task> task, Action<Exception>? onException = null)Task RunInBackground(Action action, TimeSpan period, CancellationToken token, Action<Exception>? onException = null)Task RunInBackground(Func<Task> task, TimeSpan period, CancellationToken token, Action<Exception>? onException = null)void WaitInBackground(Task task, Action<Exception>? onException = null)void WaitInBackground(TaskOperation task, Action<Exception>? onException = null)void WaitInBackground(ValueTask task, Action<Exception>? onException = null)void WaitInBackground<T>(ValueTask<T> task, Action<Exception>? onException = null)
WaitInBackground observes failures without blocking. Cancellation is treated as normal completion and is not sent to the exception handler or logger.
TaskOperation (System.Threading.Tasks)
TaskOperation(Func<TaskOperationContext, Task> taskFunc)bool Completed { get; }string? Description { get; set; }Exception? Exception { get; }bool FaultedCompleted { get; }bool InProgress { get; }bool Paused { get; set; }Percent Progress { get; set; }bool SuccessfullyCompleted { get; }event Action<TaskOperation>? Changedevent Action<TaskOperation>? Completevoid Cancel()ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext)void Dispose()TaskAwaiter GetAwaiter()implicit operator Task(TaskOperation operation)
TaskOperation<TResult> (System.Threading.Tasks)
TaskOperation<TResult>(Func<TaskOperationContext, Task<TResult>> taskFunc)TResult Result { get; }— returns a completed result without waiting, throws before completion, and rethrows the original task error.ConfiguredTaskAwaitable<TResult> ConfigureAwait(bool continueOnCapturedContext)TaskAwaiter<TResult> GetAwaiter()implicit operator Task<TResult>(TaskOperation<TResult> operation)
TaskOperationContext (System.Threading.Tasks)
TaskOperationContext(TaskOperation task, CancellationToken token)bool Cancelled { get; }bool Paused { get; }CancellationToken Token { get; }event Action? CompleteValueTask CheckPausedAndCancelled()void SetDescription(string description)void SetProgress(Percent progress)void StopIfCancelled()Task SubTask(Func<TaskOperation> factory, Percent endProgress)Task SubTask(TaskOperation subTask, Percent endProgress)Task<TResult> SubTask<TResult>(Func<TaskOperation<TResult>> factory, Percent endProgress)Task<TResult> SubTask<TResult>(TaskOperation<TResult> subTask, Percent endProgress)
File system
File (FileSystem)
File(string path)File(string path, byte[] defaultContent)File(string path, string defaultContent)FileStream AppendingStream { get; }FileAttributes Attributes { get; set; }string Content { get; set; }byte[] ContentBytes { get; set; }DateTime CreationTime { get; set; }bool Exists { get; }string Extension { get; set; }Folder Folder { get; set; }DateTime LastAccessTime { get; set; }DateTime LastUpdateTime { get; set; }bool CanRead { get; }— reports whether the existing file can currently be opened for reading.bool CanWrite { get; }— reports whether the existing file can currently be opened for writing.bool Locked { get; }— checks whether exclusive access to the existing file is currently blocked.string Name { get; set; }string NameWithExtension { get; set; }string Path { get; set; }FileStream ReadOnlyStream { get; }DataSize Size { get; }FileStream Stream { get; }void Append(IEnumerable<string> lines)void Append(byte[] content)void Append(string content)void Clear()void CopyTo(Folder folder, bool overwrite = true)bool Equals(File? other)bool Equals(object? obj)void ExtractZip(Folder folder)int GetHashCode()void Overwrite(byte[] content)void Overwrite(string content)string PathRelative(Folder folder)— returns the path relative to the folder.byte[] ReadPart(long startIndex, long length)File RelativeTo(Folder folder)void Remove()string ToString()- Same-type operators:
==,!=. implicit operator File(string path)
Folder (FileSystem)
Folder(string path)DateTime CreationTime { get; set; }bool Exists { get; }IEnumerable<File> Files { get; }int FilesCount { get; }IEnumerable<Folder> Folders { get; }DateTime LastAccessTime { get; set; }DateTime LastWriteTime { get; set; }IEnumerable<File> LocalFiles { get; }int LocalFilesCount { get; }IEnumerable<Folder> LocalFolders { get; }string Name { get; set; }Folder Parent { get; set; }string Path { get; set; }Folder RootParent { get; }DataSize Size { get; }void Clear()void CopyTo(Folder folder, bool overwrite = true)Folder Create(string path)bool Equals(Folder? other)bool Equals(object? obj)int GetHashCode()Folder RelativeTo(Folder folder)void Remove()IEnumerable<File> SearchFiles(string pattern)IEnumerable<File> SearchFilesLocal(string pattern)string ToString()File ToZipFile(Folder outputFolder, string name)- Same-type operators:
==,!=. implicit operator Folder(string path)
Enumeration includes hidden and system entries. Recursive traversal, copying, and ZIP creation follow symbolic links and junctions when the runtime can resolve them. Physical roots include links in intermediate path components. Each physical directory is processed at most once per operation, so cyclic and duplicate links are skipped. ZIP creation excludes its own output directory or file. Recursive access to a link throws PlatformNotSupportedException when the runtime cannot resolve directory links.
TempCacheFolder<TKey, TValue> (FileSystem)
Persistent cache. One instance must own a folder, and settings.json fixes the serialization algorithm for that folder.
Constraint: TKey : notnull.
TempCacheFolder(Folder folder, SerializationAlgorithm serializationAlgorithm, TimeSpan? clearPeriod = null)Folder Folder { get; }SerializationAlgorithm SerializationAlgorithm { get; }DataSize Size { get; }void Clear()void ClearOutdatedKeys()Task<bool> Contains(Func<TValue, bool> predicate, CancellationToken cancellationToken = default)bool Contains(TKey key)bool Contains(TKey key, out TValue? value)void Dispose()Task<TValue?> Find(Func<TValue, bool> predicate, CancellationToken cancellationToken = default)TValue Get(TKey key)TValue GetOrCreate(TKey key, Func<TValue> factory, TimeSpan? lifetime)void Remove(TKey key)void Set(TKey key, TValue value, TimeSpan? lifetime)bool TryAdd(TKey key, TValue value, TimeSpan? lifetime)IAsyncEnumerable<TValue> Where(Func<TValue, bool> predicate, CancellationToken cancellationToken = default)
Extensions (FileSystem)
File SaveToFile(this string content, Folder folder, string name)
HTTP
IHttpClient (Http)
Task<HttpResponse> ExecuteRequest(HttpRequest request, CancellationToken cancelToken)
SystemHttpClient (Http)
SystemHttpClient()SystemHttpClient SharedTask<HttpResponse> ExecuteRequest(HttpRequest request, CancellationToken cancelToken)
The default certificate policy and disabled validation use shared clients. A custom certificate-validation delegate receives a dedicated client for that request; the client remains alive while the response is in use and is disposed with the response.
HttpRequest (Http)
HttpRequest(HttpMethod method, string link)HttpRequest(IHttpClient client, HttpMethod method, string link)IHttpClient ClientHttpMethod MethodUri RequestUri { get; }HttpHeaderCollection HeadersHttpRequestBody? BodyTimeSpan TimeoutFolder? DownloadFolderstring? DownloadFileNamebool ReturnNullIfNotFoundint MaxRetriesPerErrorHandlerFunc<X509Certificate2, SslPolicyErrors, bool>? ValidateCertificatestring Link { get; }bool UsesDefaultCertificateValidation { get; }void AddErrorHandler(ErrorHandler errorHandler)HttpRequest AddQueryParameter(string name)HttpRequest AddQueryParameter(string name, string value)Task<HttpResponse?> Execute(CancellationToken cancelToken = default)— returns the raw response.Task<TResult?> Execute<TResult>(CancellationToken cancelToken = default)— deserializes the response content.void SetBody(byte[] bytes, string? contentType = null)void SetBody(Func<Stream> openRead, string? contentType = null, long? length = null)void SetJsonBody<T>(T value)void SetBinaryBody<T>(T value)void SetErrorHandlers(List<ErrorHandler> errorHandlers)Task<HttpResponse?> GET(string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<TResult?> GET<TResult>(string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<HttpResponse?> POST(string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<TResult?> POST<TResult>(string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<HttpResponse?> PUT(string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<TResult?> PUT<TResult>(string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<HttpResponse?> DELETE(string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<TResult?> DELETE<TResult>(string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<HttpResponse?> PATCH(string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<TResult?> PATCH<TResult>(string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)
HttpRequest.ErrorHandler (Http)
delegate Task<bool> ErrorHandler(HttpException error, CancellationToken cancellationToken)— returntrueto retry the current handler stage and observe request cancellation through the token.
HttpClientExtensions (Http)
Task<HttpResponse?> GET(this IHttpClient client, string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<TResult?> GET<TResult>(this IHttpClient client, string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<HttpResponse?> POST(this IHttpClient client, string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<TResult?> POST<TResult>(this IHttpClient client, string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<HttpResponse?> PUT(this IHttpClient client, string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<TResult?> PUT<TResult>(this IHttpClient client, string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<HttpResponse?> DELETE(this IHttpClient client, string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<TResult?> DELETE<TResult>(this IHttpClient client, string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<HttpResponse?> PATCH(this IHttpClient client, string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)Task<TResult?> PATCH<TResult>(this IHttpClient client, string link, Action<HttpRequest>? request = null, CancellationToken cancelToken = default)
HttpRequestBody (Http)
HttpRequestBody(Func<Stream> openRead, string? contentType = null, long? length = null)string? ContentTypelong? LengthHttpRequestBody FromBytes(byte[] bytes, string? contentType = null)Stream OpenRead()bool TryGetBytes(out ArraySegment<byte> bytes)
HttpHeaderCollection (Http)
Header names are compared without case sensitivity and duplicate values are preserved.
HttpHeaderCollection()int Count { get; }string? this[string name] { get; set; }void Add(IDictionary<string, string> headers)void Add(string name, string value)HttpHeaderCollection Clone()bool Contains(string name)IEnumerator<KeyValuePair<string, string>> GetEnumerator()IEnumerable<string> GetValues(string name)bool Remove(string name)
HttpResponse (Http)
HttpResponse(HttpRequest request, HttpStatusCode statusCode, string? reasonPhrase, HttpHeaderCollection headers, Stream content, IDisposable? resource = null)HttpRequest RequestHttpStatusCode StatusCodestring? ReasonPhraseHttpHeaderCollection HeadersCancellationToken CancellationToken { get; }Stream Content { get; }bool IsSuccessStatusCode { get; }void Dispose()ValueTask DisposeAsync()void EnsureSuccessStatusCode()Task<TResult?> ReadContentAs<TResult>(CancellationToken cancelToken = default)
HttpException (Http)
HttpException(HttpStatusCode statusCode, string? reasonPhrase, HttpRequest request, HttpHeaderCollection headers, byte[] content)byte[] ContentHttpHeaderCollection Headersstring? ReasonPhraseHttpRequest RequestHttpStatusCode StatusCodeHttpResponse Response { get; }
Extensions (Http)
void Add(this HttpHeaders httpHeaders, IDictionary<string, string> headers)
WebSockets
SendBandwidth and ReceiveBandwidth are unlimited when null. The system transport applies limits independently, keeps outgoing messages queued without dropping them, and reacts to runtime limit changes.
Bandwidth (WebSockets)
Bandwidth(DataSize size, TimeSpan interval)DataSize SizeTimeSpan Intervalbool Equals(Bandwidth other)bool Equals(object? obj)int GetHashCode()- Same-type operators:
==,!=
IWebSocketTransport (WebSockets)
bool Connected { get; }Bandwidth? ReceiveBandwidth { get; set; }Bandwidth? SendBandwidth { get; set; }event Action<WebSocketCloseStatus?, string?>? Closedevent Action<Exception>? Errorevent Action<WebSocketMessageType, ArraySegment<byte>, bool>? MessageFragmentReceivedTask Connect(string link, WebSocketConnectOptions options, CancellationToken cancellationToken = default)Task Disconnect(WebSocketCloseStatus closeStatus = WebSocketCloseStatus.NormalClosure, string? description = null, CancellationToken cancellationToken = default)Task SendBytes(ArraySegment<byte> bytes, CancellationToken cancellationToken = default)Task SendText(string text, CancellationToken cancellationToken = default)
SystemWebSocketTransport (WebSockets)
SystemWebSocketTransport()bool Connected { get; }Bandwidth? ReceiveBandwidth { get; set; }Bandwidth? SendBandwidth { get; set; }event Action<WebSocketCloseStatus?, string?>? Closedevent Action<Exception>? Errorevent Action<WebSocketMessageType, ArraySegment<byte>, bool>? MessageFragmentReceivedTask Connect(string link, WebSocketConnectOptions options, CancellationToken cancellationToken = default)Task Disconnect(WebSocketCloseStatus closeStatus = WebSocketCloseStatus.NormalClosure, string? description = null, CancellationToken cancellationToken = default)void Dispose()— cancels an in-progress connection attempt and closes the active connection.WebSocket FromConnection(System.Net.WebSockets.WebSocket connection, Action<WebSocket>? configure = null)— takes ownership of the connection and disposes it if configuration fails.Task SendBytes(ArraySegment<byte> bytes, CancellationToken cancellationToken = default)Task SendText(string text, CancellationToken cancellationToken = default)
Transport events invoke subscribers independently; a failing subscriber is logged and does not prevent later subscribers from running.
WebSocket (WebSockets)
WebSocket()WebSocket(IWebSocketTransport transport)Func<IWebSocketTransport> DefaultTransportProvider { get; set; }bool Connected { get; }CancellationToken DisposeToken { get; }DataSize MaxMessageSize { get; set; }Bandwidth? ReceiveBandwidth { get; set; }Bandwidth? SendBandwidth { get; set; }event Action<ArraySegment<byte>>? BytesReceivedevent Action<WebSocketCloseStatus?, string?>? Closedevent Action? Disposedevent Action<string>? TextReceivedevent Action<Exception>? WhenErrorTask Connect(string link, Action<WebSocketConnectOptions>? configure = null, CancellationToken cancellationToken = default)Task Disconnect(CancellationToken cancellationToken = default)void Dispose()void Send(ArraySegment<byte> bytes)void Send(string text)void SendMessage<TEnum, T>(TEnum type, T? value = default) where TEnum : struct, EnumIDisposable SubscribeOnMessageReceive<TEnum>(Action<IMessage<TEnum>> handler) where TEnum : struct, Enum
WebSocketConnectOptions (WebSockets)
WebSocketConnectOptions()HttpHeaderCollection HeadersTimeSpan KeepAliveIntervalList<string> SubProtocolsTimeSpan Timeout
Remote connections
IRemoteConnection (Network)
bool Connected { get; }event Action? Disconnectedevent Action<ArraySegment<byte>>? MessageReceivedTask SendMessage(ArraySegment<byte> message, CancellationToken cancellationToken = default)
Extensions (Network)
RemoteConnection<TRequestType> AsRemoteConnection<TRequestType>(this IRemoteConnection connection) where TRequestType : struct, Enum
RemoteConnection<TRequestType> (Network)
Typed request/response protocol over an IRemoteConnection. Supports up to eight request arguments.
Constraint: TRequestType : struct, Enum.
RemoteConnection(IRemoteConnection connection)int ApproximateMessageSize { get; set; }bool Connected { get; }int MaxConcurrentHandlers { get; set; }TimeSpan Timeout { get; set; }event Action? Disconnectedevent Action<Exception>? Errorvoid Dispose()IDisposable AddRequestHandler<TResult>(TRequestType requestType, Func<TResult> handler)IDisposable AddRequestHandler<T1, TResult>(TRequestType requestType, Func<T1, TResult> handler)IDisposable AddRequestHandler<T1, T2, TResult>(TRequestType requestType, Func<T1, T2, TResult> handler)IDisposable AddRequestHandler<T1, T2, T3, TResult>(TRequestType requestType, Func<T1, T2, T3, TResult> handler)IDisposable AddRequestHandler<T1, T2, T3, T4, TResult>(TRequestType requestType, Func<T1, T2, T3, T4, TResult> handler)IDisposable AddRequestHandler<T1, T2, T3, T4, T5, TResult>(TRequestType requestType, Func<T1, T2, T3, T4, T5, TResult> handler)IDisposable AddRequestHandler<T1, T2, T3, T4, T5, T6, TResult>(TRequestType requestType, Func<T1, T2, T3, T4, T5, T6, TResult> handler)IDisposable AddRequestHandler<T1, T2, T3, T4, T5, T6, T7, TResult>(TRequestType requestType, Func<T1, T2, T3, T4, T5, T6, T7, TResult> handler)IDisposable AddRequestHandler<T1, T2, T3, T4, T5, T6, T7, T8, TResult>(TRequestType requestType, Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> handler)IDisposable AddAsyncRequestHandler<TResult>(TRequestType requestType, Func<CancellationToken, Task<TResult>> handler)IDisposable AddAsyncRequestHandler<T1, TResult>(TRequestType requestType, Func<T1, CancellationToken, Task<TResult>> handler)IDisposable AddAsyncRequestHandler<T1, T2, TResult>(TRequestType requestType, Func<T1, T2, CancellationToken, Task<TResult>> handler)IDisposable AddAsyncRequestHandler<T1, T2, T3, TResult>(TRequestType requestType, Func<T1, T2, T3, CancellationToken, Task<TResult>> handler)IDisposable AddAsyncRequestHandler<T1, T2, T3, T4, TResult>(TRequestType requestType, Func<T1, T2, T3, T4, CancellationToken, Task<TResult>> handler)IDisposable AddAsyncRequestHandler<T1, T2, T3, T4, T5, TResult>(TRequestType requestType, Func<T1, T2, T3, T4, T5, CancellationToken, Task<TResult>> handler)IDisposable AddAsyncRequestHandler<T1, T2, T3, T4, T5, T6, TResult>(TRequestType requestType, Func<T1, T2, T3, T4, T5, T6, CancellationToken, Task<TResult>> handler)IDisposable AddAsyncRequestHandler<T1, T2, T3, T4, T5, T6, T7, TResult>(TRequestType requestType, Func<T1, T2, T3, T4, T5, T6, T7, CancellationToken, Task<TResult>> handler)IDisposable AddAsyncRequestHandler<T1, T2, T3, T4, T5, T6, T7, T8, TResult>(TRequestType requestType, Func<T1, T2, T3, T4, T5, T6, T7, T8, CancellationToken, Task<TResult>> handler)Task<TResult?> SendRequest<TResult>(TRequestType requestType, CancellationToken cancellationToken = default)Task<TResult?> SendRequest<T1, TResult>(TRequestType requestType, T1? arg1, CancellationToken cancellationToken = default)Task<TResult?> SendRequest<T1, T2, TResult>(TRequestType requestType, T1? arg1, T2? arg2, CancellationToken cancellationToken = default)Task<TResult?> SendRequest<T1, T2, T3, TResult>(TRequestType requestType, T1? arg1, T2? arg2, T3? arg3, CancellationToken cancellationToken = default)Task<TResult?> SendRequest<T1, T2, T3, T4, TResult>(TRequestType requestType, T1? arg1, T2? arg2, T3? arg3, T4? arg4, CancellationToken cancellationToken = default)Task<TResult?> SendRequest<T1, T2, T3, T4, T5, TResult>(TRequestType requestType, T1? arg1, T2? arg2, T3? arg3, T4? arg4, T5? arg5, CancellationToken cancellationToken = default)Task<TResult?> SendRequest<T1, T2, T3, T4, T5, T6, TResult>(TRequestType requestType, T1? arg1, T2? arg2, T3? arg3, T4? arg4, T5? arg5, T6? arg6, CancellationToken cancellationToken = default)Task<TResult?> SendRequest<T1, T2, T3, T4, T5, T6, T7, TResult>(TRequestType requestType, T1? arg1, T2? arg2, T3? arg3, T4? arg4, T5? arg5, T6? arg6, T7? arg7, CancellationToken cancellationToken = default)Task<TResult?> SendRequest<T1, T2, T3, T4, T5, T6, T7, T8, TResult>(TRequestType requestType, T1? arg1, T2? arg2, T3? arg3, T4? arg4, T5? arg5, T6? arg6, T7? arg7, T8? arg8, CancellationToken cancellationToken = default)
RemoteRequestErrorCode (Network)
- Values:
HandlerNotFound,InvalidRequest,HandlerFailed,Busy,Rejected
RemoteRequestException (Network)
RemoteRequestException(RemoteRequestErrorCode errorCode, string message)RemoteRequestErrorCode ErrorCode { get; }
RemoteConnectionClosedException (Network)
RemoteConnectionClosedException()
Localization
IStringSource (Localization)
string GetString(string id)
Language (Localization)
Language(string name, IStringSource stringSource, Language.Culture culture = Language.Culture.Invariant)Language(string name, IStringSource stringSource, string cultureName)string NameIStringSource StringSourcestring CultureNameCultureInfo CultureInfobool HasSpecificCultureDayOfWeek WeekStartDay { get; set; }TimeFormatInfo TimeFormat { get; }NumberFormatInfo NumberFormat { get; }DateTimeFormatInfo DateTimeFormat { get; }T GetSetting<T>()void SetSetting<T>(T value)bool TryGetSetting<T>(out T? value)
Language.Culture (Localization)
- Values:
Invariant,ArabicSaudiArabia,Belarusian,Bulgarian,ChineseSimplified,ChineseTraditional,Croatian,Czech,Danish,Dutch,EnglishUnitedKingdom,EnglishUnitedStates,Finnish,French,German,Greek,Hebrew,Hindi,Hungarian,Indonesian,Italian,Japanese,Korean,NorwegianBokmal,NorwegianNynorsk,Polish,PortugueseBrazil,PortuguesePortugal,Romanian,Russian,SerbianCyrillic,SerbianLatin,Slovak,Spanish,Swedish,Thai,Turkish,Ukrainian,Vietnamese.
Localization (Localization)
const string LocalizeStringTagName = "localize"Language? Language { get; set; }IReadOnlyCollection<Language> Languages { get; }event Action? LanguageChangedvoid Add(Language language)string CreateLocalizeTag(string id)T GetSetting<T>()string GetString(string id)void Remove(Predicate<Language> predicate)bool TryGetSetting<T>(out T? value)IDisposable UseLanguage(Language language)
Assigning Language changes the global program language and the default culture for application threads. UseLanguage temporarily overrides the language, CurrentCulture, and CurrentUICulture only in the current asynchronous context; the override flows through await, supports nesting, and is restored when disposed. The Language getter returns the scoped language when one exists. LanguageChanged reports global changes only and invokes subscribers independently.
LocalizationExtensions (Localization)
string Localize(this string text)string ToStringAsTimer(this TimeSpan time)
TimeFormatInfo (Localization)
TimeFormatInfo()string DaysLetter { get; set; }string HoursLetter { get; set; }string MinutesLetter { get; set; }string SecondsLetter { get; set; }
Local data
LocalStorage (LocalData)
LocalStorage(IKeyValueStorage storage)LocalStorage(File file)IKeyValueStorage Storage { get; }void Set<T>(string key, T value)T Get<T>(string key)T Get<T>(string key, Func<T> defaultValue)bool Contains(string key)bool Contains<T>(string key, out T? value)void Remove(string key)
LocalStorageValue<T> (LocalData)
Constraint: T : notnull.
LocalStorageValue(IKeyValueStorage storage, string key, Func<T>? defaultValue = null)bool Exists { get; }T Value { get; set; }bool Equals(LocalStorageValue<T>? other)bool Equals(T? other)bool Equals(object? obj)int GetHashCode()void Remove()void Update(T value)- Same-type operators:
==,!=. implicit operator T(LocalStorageValue<T> value)
KeyValueFileStorage (LocalData)
KeyValueFileStorage(File file)File IndexFile { get; }void Set<T>(string key, T value)T Get<T>(string key)bool Contains(string key)void Remove(string key)
Stores raw values in one readable, indented JSON object. The storage location is fixed when the instance is created. Only one instance may work with a given storage file in one process. Index rebuilding and mutations process values through streams instead of loading the whole document. The optional adjacent index stores byte ranges and is rebuilt automatically when missing or invalid. Mutations atomically replace the JSON file.
EncryptedKeyValueStorage (LocalData)
Encrypts values and obscures keys while delegating persistence to another IKeyValueStorage.
EncryptedKeyValueStorage(IKeyValueStorage parent, string password)void Set<T>(string key, T value)T Get<T>(string key)bool Contains(string key)void Remove(string key)
Binary serialization
BinarySerializer (Serialization.Binary)
The binary format is optimized for speed and compactness. Writer and reader must use the same type contract; schema migration and polymorphic runtime-type metadata are intentionally not provided. Multidimensional zero-based arrays preserve every dimension. Delegate values are intentionally ignored and deserialize as null.
The reader does not impose collection-size, recursion-depth, or cyclic-reference limits. Use this format only for trusted data and acyclic object graphs. Binary format changes do not include backward compatibility or migration.
Standard collection interfaces are restored with standard implementations: IList<T>, ICollection<T>, IReadOnlyList<T>, and IReadOnlyCollection<T> use List<T>; ISet<T> uses HashSet<T>; dictionary interfaces use Dictionary<TKey, TValue>. Concrete implementation-specific state is not preserved through an interface contract.
void Change<T>(WriteConverter<T> writeConverter, ReadConverter<T> readConverter)void Serialize<T>(Stream stream, T? value)void Serialize(Stream stream, object? value, Type type)T? Deserialize<T>(Stream stream)object? Deserialize(Stream stream, Type type)
BinarySerializer.ReadConverter (Serialization.Binary)
delegate object? ReadConverter(Stream stream)
BinarySerializer.ReadConverter<T> (Serialization.Binary)
delegate T? ReadConverter<T>(Stream stream)
BinarySerializer.WriteConverter (Serialization.Binary)
delegate void WriteConverter(Stream stream, object? value)
BinarySerializer.WriteConverter<T> (Serialization.Binary)
delegate void WriteConverter<T>(Stream stream, T? value)
Generated serialization infrastructure
These types are public so generated code can register itself. Application code normally uses ToJson, ToBytes, and the corresponding read methods instead.
GeneratedBinarySerializers (Serialization.Generated)
T CreateUninitialized<T>()
GeneratedJsonSerializers (Serialization.Generated)
void Change<T>(JsonConverter<T> converter)
GeneratedJsonConverterFactory (Serialization.Generated)
GeneratedJsonConverterFactory()bool CanConvert(Type typeToConvert)JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
GeneratedSerializationProviderAttribute (Serialization.Generated)
GeneratedSerializationProviderAttribute(Type providerType)Type ProviderType
GeneratedSerializationRegistry (Serialization.Generated)
void Refresh()
GeneratedTypeRegistry (Serialization.Generated)
int GetId(Type type)Type Resolve(int id)
IGeneratedSerializationProvider (Serialization.Generated)
int TypeCount { get; }Type GetType(int index)int GetTypeId(int index)void Register()bool TryGetTypeId(Type type, out int id)bool TryResolveType(int id, out Type? type)
PreserveAttribute (Serialization.Generated)
PreserveAttribute()
Code generation
AccessModifier (CodeGeneration)
- Values:
Public,Private,Protected,Internal,ProtectedInternal,PrivateProtected
ScriptType (CodeGeneration)
- Values:
Class,Record,Struct,Interface,SealedClass,AbstractClass
Extensions (CodeGeneration)
string NameToCSharp(this Type type)string ToArgsString(this IEnumerable<(string type, string name)> args)string ToCSharp(this AccessModifier modifier)string ToCSharp(this ScriptType type)
EnumBuilder (CodeGeneration)
EnumBuilder(string name, AccessModifier accessModifier = AccessModifier.Public)AccessModifier AccessModifierstring Namevoid Add(IEnumerable<string> values)void Add(string value)File SaveToFile(Folder folder)string ToString()
ScriptBuilder (CodeGeneration)
ScriptBuilder(ScriptType type, string name, string? @namespace = null, AccessModifier accessModifier = AccessModifier.Public)string Content { get; }string FileName { get; }string Name { get; }string? Namespace { get; }void Add(string code)void AddInNamespace(string code)void AddMember(string member)void AddMethod(string @interface, Action? body)void AddUsing(string @namespace)void AddUsingForTypeIfNeeded(Type type)void AddUsings(IEnumerable<string> namespaces)void AppendLastLine(string code)void Block(Action body, bool newLineEnding = true)void Edit(Func<string, string> edit)void Line(string line)void NewLine()void NewLine(string line)void RemoveAllUsing(Predicate<string> predicate)void RemoveLines(Predicate<string> predicate)void RemoveUsing(string @namespace)void RemoveUsings()File SaveToFile(Folder folder)void SetBaseType(Type type)string ToString()
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.1 is compatible. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.1
- System.IO.Hashing (>= 10.0.10)
- System.Text.Json (>= 10.0.9)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|