Documentation

A small, focused set of C# extension methods that make every day .NET work more pleasant. Covers strings, enums, collections, objects, dates, numbers…

A small, focused set of C# extension methods that make every day .NET work more pleasant. Covers strings, enums, collections, objects, dates, numbers, comparisons, and exceptions. Lightweight and fully unit-tested.

Installation

NuGet:

# Package Manager
Install-Package ArturRios.Extensions

# .NET CLI
dotnet add package ArturRios.Extensions

Git submodule:

# add under ./lib/ArturRios.Extensions
git submodule add https://github.com/artur-rios/dotnet-extensions lib/ArturRios.Extensions

Then reference the project from your solution:

<ProjectReference Include="lib/ArturRios.Extensions/src/ArturRios.Extensions.csproj"/>

Supported frameworks

  • .NET 10.0 (net10.0)

Dependencies

A couple of small NuGet packages are pulled in transitively:

  • ArturRios.Util — shared regex and math helpers used by the string and number extensions.
  • Newtonsoft.Json — used for deep cloning in Clone<T>().

Quick start

Add a using to bring extensions into scope and call them like any other instance method:

using ArturRios.Extensions;

var hasLower = "AbC".HasLowerChar();     // true
var hasUpper = "abc".HasUpperChar();     // false
var hasNumber = "a1b".HasNumber();       // true

var okMin = "ab".HasMinLength(2);        // true
var okMax = "abcd".HasMaxLength(3);      // false

var isEmail = "[email protected]".IsValidEmail();   // true
var idn     = "user@héllo.com".IsValidEmail();      // true - the domain is punycoded first

var cleaned = "xxvaluexx".TrimChar('x'); // "value"

var value = ((string?)null).ValueOrDefault("fallback"); // "fallback"

var numbers = new[] { 1, 2, 3 };
var printed = numbers.JoinWith(" | "); // "1 | 2 | 3"

var inSet = 2.In(0, 2, 4);              // true
var notIn = 3.NotIn(0, 2, 4);           // true

var at = new DateTime(2025, 12, 10, 15, 30, 45, 999).RemoveMilliseconds();
// 2025-12-10 15:30:45.000

var prime = 7.IsPrime();                 // true

API overview

Below is a summary of the most commonly used extension methods with short examples. See source files under src/ and unit tests under tests/ for the full list and behavior.

String extensions (StringExtensions)

  • HasLowerChar() / HasUpperChar() / HasNumber()
    • True/false checks for at least one lower/upper/digit character.
  • HasMinLength(int min) / HasMaxLength(int max)
    • Length guardrails. Declared on a non-null string; an empty string has length 0.
  • IsValidEmail()
    • Delegates to ArturRios.Util.Text.EmailAddress.IsValid, so the domain is lowercased and punycoded before the syntax check. Mixed-case and internationalized domains are accepted.
  • TrimChar(char c)
    • Trims whitespace from both ends, then trims the given character from the result. The two passes run once each in that order, so "- a -".TrimChar('-') is " a ". Empty input comes back unchanged.
  • ValueOrDefault(string? defaultValue = null)
    • Returns the string when it has a value; otherwise the provided default. Treats null/empty as no value.
  • ParseToBoolOrDefault(bool? defaultValue = null) / ParseToIntOrDefault(int? defaultValue = null)
    • Safe parsing to bool? / int? that returns the provided default — null unless you pass one — on invalid or null input. Integers are parsed with the invariant culture, so "-5" is -5 whatever the machine’s culture.
  • ParseToObjectOrDefault<T>()
    • Parses JSON into T; returns null on invalid or empty input. Property names match regardless of case, so {"name":"Ana"} binds to a Name property.
  • IsValidEnumValue<TEnum>(bool ignoreCase = true)
    • Checks if a string names a declared member of the enum. Case-insensitive by default, and surrounding whitespace is tolerated. A numeric string is accepted only when the number it denotes is a declared member, so "999" is rejected by a three-member enum.
  • JoinWith(string separator = ", ") (for IEnumerable<string> and any IEnumerable<T>)
    • Concatenates elements with a separator, converting other element types via ToString() and allowing null.

Enumerable extensions (EnumerableExtensions)

  • IsEmpty() / IsNotEmpty()
    • Works for any IEnumerable. Avoids materializing where possible.
  • PrintContents()
    • Writes primitive items directly and complex object properties to Console.Out. Handles null enumerable. Enums, Guid, DateTime, DateTimeOffset, DateOnly, TimeOnly and TimeSpan items print as one value; static properties and indexers are skipped.

Enum extensions (EnumExtensions)

  • GetDescription()
    • Returns the DescriptionAttribute value for an enum member, or null when absent.

Object extensions (ObjectExtensions)

  • NonNullPropertiesToDictionary() / PropertiesToDictionary()
    • Reflects an object into a dictionary of property names to values, optionally skipping null values. Only public, readable instance properties are included: static properties, indexers and write-only properties are skipped.

Generic extensions (GenericExtensions)

  • Clone<T>()
    • Deep clone via a JSON round trip. Returns null when the source is null, and throws when the graph cannot be round-tripped — a reference cycle, for example. The clone is only as faithful as the round trip: members the serializer ignores are absent, and reference identity within the graph is not kept.

DateTime extensions (DateTimeExtensions)

  • RemoveMilliseconds()
    • Truncates to whole seconds, preserving the DateTimeKind. Every sub-second component goes, not only the milliseconds: microseconds and the remaining ticks go with them.

Int extensions (IntExtensions)

  • IsPrime()
    • Determines whether an integer is prime. Available for every integral type (int, long, short, byte, and the uint/ulong/ushort/sbyte variants).

Comparison extensions (ComparisonExtensions)

  • In<T>(params T[] range) / NotIn<T>(params T[] range)
    • Membership helpers for readability. Equality is decided by EqualityComparer<T>.Default, so two nulls compare equal and a type’s own Equals / IEquatable<T> is honoured. An empty range never matches; a null range throws ArgumentNullException.

Exception extensions (ExceptionExtensions)

  • ToLogLine(out Guid traceId)
    • Produces a single-line log string with timestamp, trace id, exception type, message, and stack trace. Line breaks in the message and stack trace are escaped as \n, so one exception is always one line. Throws NullReferenceException when called on null.

Usage notes

  • All methods are static extensions under the ArturRios.Extensions namespace.
  • The library prioritizes clarity and safety: methods are null-aware where the receiver is declared nullable, and avoid throwing on common invalid input. Where a receiver is declared non-null — the string validation helpers, for instance — calling it on null is a compiler warning and a runtime failure, not a silent false.
  • Uses BCL APIs like System.Text.Json and reflection where applicable, plus a couple of small NuGet dependencies (see Dependencies).

This project is licensed under the Artur Rios Attribution License. It is free and open source: you may view, use, fork, modify, and extend it, provided you credit the author, Artur Rios, with a link to artur-rios.tech or github.com/artur-rios.


Changelog

Notable changes in each release.

Contributing

Building from source, running the tests, branching and releasing.