CSharpEssentials.Core 8.0.0

dotnet add package CSharpEssentials.Core --version 8.0.0
                    
NuGet\Install-Package CSharpEssentials.Core -Version 8.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CSharpEssentials.Core" Version="8.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CSharpEssentials.Core" Version="8.0.0" />
                    
Directory.Packages.props
<PackageReference Include="CSharpEssentials.Core" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add CSharpEssentials.Core --version 8.0.0
                    
#r "nuget: CSharpEssentials.Core, 8.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package CSharpEssentials.Core@8.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=CSharpEssentials.Core&version=8.0.0
                    
Install as a Cake Addin
#tool nuget:?package=CSharpEssentials.Core&version=8.0.0
                    
Install as a Cake Tool

CSharpEssentials.Core

Utilities and extensions for everyday .NET development, with no internal dependencies.

Benchmarks against the BCL, Humanizer.Core 3.0.10 and CSharpVitamins.ShortGuid 2.0.0 (case conversion, GUID text and creation, random items, WithCancellation) are in BENCHMARKS.md.

Features

  • String case conversions: Pascal, Camel, Snake, Kebab, Macro, Train, Title, UnderscoreCamel.
  • Collection helpers for conditional add and filter, null filtering, random selection, set comparison and AllTrue / AllFalse.
  • IsBetween / IsBetweenExclusive range checks for any IComparable<T>.
  • Null-safe execution (IfNotNull, IfNull, IfTrue, IfFalse), IsNull / IsNotNull, and string IsEmpty / IsNotEmpty.
  • WithCancellation (for Task, Task<T>, ValueTask, ValueTask<T>), AsTask and AsValueTask.
  • URL-safe Base64 encoding of GUIDs, and version 7 and strictly increasing version 7 GUIDs on every target.
  • Helpers that flatten inner exceptions and their messages.
  • Common HTTP status codes as int constants (HttpCodes).
  • ITransactionRunner, a transaction abstraction that data-access packages implement.

Installation

dotnet add package CSharpEssentials.Core

Targets net11.0, net10.0, net9.0, netstandard2.1 and netstandard2.0.

Usage

String case conversions

using CSharpEssentials.Core;

string text = "helloWorld";

text.ToPascalCase();          // "HelloWorld"
text.ToCamelCase();           // "helloWorld"
text.ToSnakeCase();           // "hello_world"
text.ToKebabCase();           // "hello-world"
text.ToMacroCase();           // "HELLO_WORLD"
text.ToTrainCase();           // "Hello-World"
text.ToTitleCase();           // "Hello World"
text.ToUnderscoreCamelCase(); // "_helloWorld"

The converters keep letters of every script, combining marks and decimal digits (Unicode categories Lu, Ll, Lt, Lm, Lo, Mn, Mc and Nd); any other character starts a new word and is dropped. A word starts at an uppercase or titlecase letter, at a digit, and after a dropped character. Letters without case, such as CJK, Arabic, Hebrew or Thai, are kept as they are and continue the current word, so "用户名".ToSnakeCase() is "用户名" and "user用户Name".ToSnakeCase() is "user用户_name". Titlecase letters such as Dž are lowercased like uppercase letters. Letters outside the Basic Multilingual Plane (surrogate pairs) are still dropped. EF Core LegacySnakeCase storage and the Enums generator's SnakeCase and KebabCase output use the same rule.

Collection extensions

var list = new List<string> { "a", "b" };

list.IfAdd(true, "c");
list.IfAddRange(true, ["d", "e"]);

IEnumerable<string> source = list;
source.ForEach(Console.WriteLine).ToList();

var filtered = list.WhereIf(true, x => x != "a");
var clean = new List<string?> { "a", null, "b" }.WithoutNulls();

var numbers = new[] { 1, 2, 3 };
numbers.GetRandomItem();
numbers.GetRandomItems(2);

new List<string> { "a", "b" }.HasSameElements(["b", "a"]);  // true (order and duplicates ignored)
new[] { true, true }.AllTrue();                                // true
new[] { false, false }.AllFalse();                             // true

ForEach on IEnumerable<T> is lazy: it runs the action for each item while the result is enumerated, so nothing happens until you iterate it (for example with ToList()). On a List<T> the built-in List<T>.ForEach is chosen instead. GetRandomItem and GetRandomItems use RandomNumberGenerator, pick unique items and work on T[], List<T> and Span<T>.

Range checks

5.IsBetween(1, 10);            // true  (inclusive)
10.IsBetweenExclusive(1, 10);  // false (exclusive)
orderDate.IsBetween(start, end);

Functional extensions

object? data = GetData();

if (data.IsNull()) { /* ... */ }
if (data.IsNotNull()) { /* ... */ }

data.IfNotNull(d => Process(d));
data.IfNull(() => Initialize());

string? name = null;
name.IsEmpty();      // true for null, "" and whitespace
name.IsNotEmpty();   // false

Each overload returns a bool: whether the value was not null (IfNotNull) or null (IfNull). Both also take an else action:

data.IfNotNull(d => Process(d), () => Initialize());
data.IfNull(() => Initialize(), d => Process(d));

true.IfTrue(() => Console.WriteLine("yes"));
false.IfFalse(() => Console.WriteLine("no"));

Task helpers

await SomeTask().WithCancellation(cts.Token);

string value = "hello";
Task<string> task = value.AsTask();
ValueTask<string> vt = value.AsValueTask();

WithCancellation stops waiting and throws OperationCanceledException when the token is cancelled. On .NET 9 and later it is Task.WaitAsync, so the exception is the TaskCanceledException subclass and carries the token. It does not cancel the underlying task, and it returns the original task when the token cannot be cancelled.

GUID utilities

Guid id = Guider.NewGuid();          // Version 7 on every target
Guid ordered = Guider.NewMonotonicGuid(); // Version 7, strictly increasing in this process
Guid sqlKey = Guider.NewSqlServerGuid();  // Version 8, ordered for SQL Server uniqueidentifier
string shortId = id.ToStringFromGuid(); // URL-safe, 22 chars
Guid parsed = shortId.ToGuidFromString();

The string is RFC 4648 base64url without padding: standard Base64 with + replaced by - and / replaced by _. Any base64url codec, such as System.Buffers.Text.Base64Url on .NET 9+, decodes it to the same GUID, and ToGuidFromString accepts strings that codec produces. A last character with non-zero unused bits decodes to the same GUID as the canonical string on every runtime; any other malformed input throws FormatException.

Guider.ToStringFromGuid and Guider.ToGuidFromString are the static forms. See Guids.

Other helpers

ex.GetInnerExceptions() and ex.GetInnerExceptionsMessages() return lazy sequences that start with ex itself, followed by each inner exception. HttpCodes holds int constants such as HttpCodes.Ok, HttpCodes.NotFound and HttpCodes.BadRequest.

object boxed = 42;
int number = boxed.ExplicitCast<int>();

DateTime when = 1700000000000L.MsToDateTime();   // Unix milliseconds, Kind is Utc

HttpGroup group = HttpStatus.BadRequest.GetTypeGroup<HttpGroup, HttpStatus>();  // HttpGroup.ClientError

public enum HttpStatus { Ok = 200, BadRequest = 400 }
public enum HttpGroup { Success = 200, ClientError = 400 }

GetTypeGroup rounds the enum value down to a multiple of group (default 100) and converts it to the target enum.

On .NET 10 and later, using CSharpEssentials; also brings the C# 14 extension members IEnumerable<T>.IsEmpty (property, !source.Any()) and string.IsPalindrome (property).

Transaction runner abstraction

ITransactionRunner (namespace CSharpEssentials.Transactions) runs a unit of work in a transaction and commits only when shouldCommit returns true. It has no dependencies, so data-access packages implement it (EfCoreTransactionRunner<TDbContext> in CSharpEssentials.EntityFrameworkCore) and pipelines consume it (TransactionBehavior in CSharpEssentials.Mediator).

using CSharpEssentials.ResultPattern;
using CSharpEssentials.Transactions;

Result result = await transactionRunner.ExecuteAsync(
    ct => handler.Handle(command, ct),
    outcome => outcome.IsSuccess,
    cancellationToken);

Here handler.Handle returns ValueTask<Result>; Result comes from CSharpEssentials.Results.

Upgrading to 8.0

  • GetRandomItems throws ArgumentOutOfRangeException (parameter count) for a negative count. It threw OverflowException before; update any catch that relied on that.
  • MsToDateTime returns a DateTime with Kind = Utc. It returned Kind = Unspecified before, with the same ticks. ToUniversalTime() no longer shifts it by the local offset, System.Text.Json now writes a trailing Z, and Npgsql maps it to timestamp with time zone. If you stored or compared the old value, call DateTime.SpecifyKind(value, DateTimeKind.Unspecified) to keep the old behaviour.
  • ToSnakeCase, ToKebabCase and the other case converters keep letters without case (CJK, Arabic, Hebrew, Thai), titlecase letters and combining marks. 7.x dropped them, so "用户名".ToSnakeCase() was "" and "user用户Name" was "user_name"; they are now "用户名" and "user用户_name". Output for names written only in Latin letters and digits does not change. If you stored converted values of non-Latin names, for example through EF Core LegacySnakeCase enum storage, rewrite them with the new output.
  • ToStringFromGuid and ToGuidFromString use the RFC 4648 base64url alphabet (+ as -, / as _). 7.x used the reverse mapping, so a short ID stored by 7.x that contains - or _ now decodes to a different GUID. Convert stored IDs once by swapping every - with _ and every _ with -, for example id.Replace('-', '*').Replace('_', '-').Replace('*', '_').
  • Guider.NewGuid() on the netstandard2.0 and netstandard2.1 assets, and so on .NET 8 and .NET Framework, returns RFC 9562 version 7 GUIDs instead of version 4. The first 6 bytes hold the creation time. Use Guid.NewGuid() where an ID must not reveal when it was created. On every target the random bits now come from a per-thread pool; apps that run in a cloned virtual machine or a checkpointed and restored process should read Cloned processes.
  • WithCancellation on the .NET 9, 10 and 11 targets throws TaskCanceledException, a subclass of OperationCanceledException, when the token is cancelled. 7.x threw OperationCanceledException itself. A catch (OperationCanceledException) still catches it, but an exact type check such as ex.GetType() == typeof(OperationCanceledException) or xUnit Assert.ThrowsAsync<OperationCanceledException> no longer matches. The netstandard2.0 and netstandard2.1 assets still throw OperationCanceledException.
Product 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 is compatible.  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 is compatible.  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.  net11.0 is compatible. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (6)

Showing the top 5 NuGet packages that depend on CSharpEssentials.Core:

Package Downloads
CSharpEssentials.Errors

Comprehensive error handling system for functional programming in C#. Provides Error types, ErrorMetadata, ErrorType enums, and extensions for robust error management. Foundation for Result pattern and functional error handling.

CSharpEssentials

A comprehensive C# library enhancing functional programming capabilities with type-safe monads (Maybe, Result), discriminated unions (Any), and robust error handling. Features include: domain-driven design support, enhanced Entity Framework integration, testable time management, JSON utilities, and LINQ extensions. Built for modern C# development with focus on maintainability, testability, and functional programming principles.

CSharpEssentials.EntityFrameworkCore

Enhances Entity Framework Core with functional programming patterns and DDD-friendly features. Includes base entity classes, soft delete support, audit trails, query filters, optimistic concurrency, PostgreSQL integration, query performance monitoring, and domain event handling. Perfect for building maintainable and scalable data access layers in modern .NET applications.

CSharpEssentials.GcpSecretManager

A powerful .NET configuration provider for Google Cloud Secret Manager that enables seamless secret management in your applications. Features include region-specific secret handling, flexible filtering options, batch processing, automatic secret rotation, built-in retry policies, and JSON value flattening support. Perfect for cloud-native applications requiring secure and scalable secret management.

CSharpEssentials.Rules

Business rules engine for domain-driven design in C#. Provides rule validation, business logic enforcement, and domain rule composition patterns. Essential for implementing complex business rules in a maintainable way.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
8.0.0 412 11/9/2026
7.0.0 599 10/20/2026
6.5.2 541 10/10/2026
6.5.1 532 10/10/2026
6.5.0 531 10/9/2026
6.4.0 518 10/9/2026
6.3.0 525 10/8/2026
6.2.0 506 10/8/2026
6.1.0 522 10/7/2026
6.0.0 536 10/7/2026
5.2.1 542 10/7/2026
5.2.0 528 10/7/2026
5.1.0 536 10/7/2026
5.0.0 534 10/6/2026
4.1.0 518 10/6/2026
4.0.0 518 10/5/2026
3.2.3 751 5/31/2026
3.2.2 612 5/31/2026
3.2.1 581 5/31/2026
3.2.0 580 5/30/2026
Loading failed