FrameworkExtensions.Corlib
1.0.2.567
See the version list below for details.
dotnet add package FrameworkExtensions.Corlib --version 1.0.2.567
NuGet\Install-Package FrameworkExtensions.Corlib -Version 1.0.2.567
<PackageReference Include="FrameworkExtensions.Corlib" Version="1.0.2.567" />
<PackageVersion Include="FrameworkExtensions.Corlib" Version="1.0.2.567" />
<PackageReference Include="FrameworkExtensions.Corlib" />
paket add FrameworkExtensions.Corlib --version 1.0.2.567
#r "nuget: FrameworkExtensions.Corlib, 1.0.2.567"
#:package FrameworkExtensions.Corlib@1.0.2.567
#addin nuget:?package=FrameworkExtensions.Corlib&version=1.0.2.567
#tool nuget:?package=FrameworkExtensions.Corlib&version=1.0.2.567
Corlib Extensions
Overview
Extension methods for core .NET types, providing additional functionality across strings, collections, math, I/O, threading, and other common operations. Supports .NET 3.5 through .NET 9.0.
Key Features
- 3,300+ Extension Methods across common .NET types
- 600+ String extensions - parsing, formatting, case conversion, text analysis, phonetics
- 900+ Math & Numeric extensions - numeric types with SIMD optimizations and hardware intrinsics
- 300+ Array extensions - array operations, slicing, algorithms
- 400+ I/O extensions - FileInfo, DirectoryInfo, Stream operations
- 350+ Collection extensions - Dictionary, List, HashSet, concurrent collections, LINQ enhancements
- 200+ Threading extensions - Interlocked operations, task management, synchronization
- 550+ Additional extensions - DateTime, TimeSpan, reflection, data access, networking
Technical Details
- T4 Code Generation - Type-safe methods generated across numeric types
- Performance Optimizations - SIMD operations, hardware intrinsics, unsafe code where beneficial
- Thread Safety - Atomic operations, concurrent collection support
- Modern C# Features - Nullable reference types, spans, ranges, pattern matching
- Multi-Framework Support - .NET 3.5 through .NET 9.0 with conditional compilation
- Dependencies - Requires FrameworkExtensions.Backports for backported language features
- Testing - Unit, integration, performance, and regression tests
Extension Methods by Type
Completeness Note: This README serves as a comprehensive reference document covering all major extension method categories and new types in the library. While the library contains lots of extension methods (many T4-generated for all numeric types), this documentation provides:
- All extension method categories with representative methods
- All new types (classes, structs, records, interfaces, enums)
- Complete coverage of public API surface
For specific overload details and parameter variations, use IntelliSense in your IDE.
Object Extensions (object)
General-purpose object manipulation and reflection utilities
- Null Checking -
IsNull(),IsNotNull()- Null reference checks with nullable annotations - Type Checking -
Is<T>(),TypeIsAnyOf()- Runtime type verification and pattern matching - Type Casting -
As<T>()- Safe type casting with generic support - Conditional Operations -
IsTrue(),IsFalse(),IsAnyOf()- Predicate-based conditionals and set membership - Conditional Execution -
WhenNull(),WhenNotNull()- Execute actions based on null state - Reflection Access -
GetProperties(),GetFields()- Retrieve object members with filtering options - State Management -
ResetDefaultValues()- Reset object fields/properties to their default values
Boolean Extensions (bool)
Boolean logic and conditional operations
- Logical Operations -
And(),Or(),Xor(),Nand(),Nor(),Equ(),Not()- Functional-style boolean operations - Conditional Execution -
When(),WhenTrue(),WhenFalse()- Execute actions/functions based on boolean value (supports both Action and Func variants) - String Conversion -
ToYesOrNoString(),ToOneOrZeroString(),ToTrueOrFalseString()- Convert to human-readable strings
Char Extensions (char)
Character testing and manipulation
- Whitespace -
IsWhiteSpace(),IsNullOrWhiteSpace(),IsNotNullOrWhiteSpace()- Whitespace checking including null character - Digit Classification -
IsDigit(),IsNotDigit()- Check if character is a digit - Case Classification -
IsUpper(),IsNotUpper(),IsLower(),IsNotLower()- Case checking - Letter Classification -
IsLetter(),IsNotLetter()- Check if character is a letter - Control Characters -
IsControl(),IsNotControl(),IsControlButNoWhiteSpace()- Control character detection - Case Conversion -
ToUpper(),ToLower()- Case conversion with optional culture parameter - Set Membership -
IsAnyOf()- Check if character is in a set - Repetition -
Repeat(count)- Create string by repeating character N times
Nullable Extensions (T?)
Operations for nullable value types
- Null Checking -
IsNull(),IsNotNull()- Check if nullable has value (with NotNullWhen attributes)
Array Extensions (TItem[])
Array operations with performance optimizations
Core Operations
CompareTo<TItem>(other, comparer)- Compare arrays with detailed changesetsSafelyClone<TItem>()- Safe array cloning with proper type handlingSwap<TItem>(firstIndex, secondIndex)- High-performance element swappingShuffle<TItem>(entropySource)- Fisher-Yates shuffle implementationQuickSort<TItem>()/QuickSorted<TItem>()- Optimized quicksortReverse<TItem>()- In-place array reversalRotateTowardsZero<TItem>()- Array rotation operations
Slicing & Partitioning
Slice<TItem>(start, length)- Create mutable array slicesReadOnlySlice<TItem>(start, length)- Create read-only array slicesSlices<TItem>(size)- Split array into chunksProcessInChunks<TItem>(chunkSize, processor)- Chunked processing
High-Performance Fill Operations
Fill(value)- Optimized fill forbyte[],ushort[],uint[],ulong[],IntPtr[]Clear()- Optimized clear for all primitive array types
Element Access & Search
GetRandomElement<TItem>(random)- Random element selectionGetValueOrDefault<TItem>(index, defaultValue)- Safe indexed accessFirst<TItem>()/Last<TItem>()/*OrDefault()- LINQ-style element accessIndexOf<TItem>(value, comparer)- Enhanced element searchingContains<TItem>(value)- Membership testing
Transformation & Aggregation
ConvertAll<TItem, TOutput>(converter)- Array transformationForEach<TItem>(action)- Element iteration with parallel supportParallelForEach<TItem>(action)- Parallel processingJoin<TItem>(separator, converter)- String joining with custom convertersSelect<TItem, TResult>(selector)- LINQ-style projectionAggregate<TItem>(func, seed)- Aggregation operations
String Extensions (string)
String manipulation methods covering parsing, formatting, and text analysis
Case Conversion
Intelligent case transformations with word boundary detection
ToPascalCase()/ToPascalCaseInvariant()- Convert to PascalCase (e.g., "hello_world" → "HelloWorld")ToCamelCase()/ToCamelCaseInvariant()- Convert to camelCase (e.g., "hello_world" → "helloWorld")ToSnakeCase()/ToSnakeCaseInvariant()- Convert to snake_case (e.g., "HelloWorld" → "hello_world")ToUpperSnakeCase()/ToUpperSnakeCaseInvariant()- Convert to UPPER_SNAKE_CASE (e.g., "HelloWorld" → "HELLO_WORLD")ToKebabCase()/ToKebabCaseInvariant()- Convert to kebab-case (e.g., "HelloWorld" → "hello-world")ToUpperKebabCase()/ToUpperKebabCaseInvariant()- Convert to UPPER-KEBAB-CASE (e.g., "HelloWorld" → "HELLO-WORLD")UpperFirst()/UpperFirstInvariant()- Capitalize first character only (e.g., "hello" → "Hello")LowerFirst()/LowerFirstInvariant()- Lowercase first character only (e.g., "Hello" → "hello")
String Manipulation & Modification
Common string transformations and editing operations
ExchangeAt(index, replacement)- Replace character at specific position (e.g., "hello".ExchangeAt(1, 'a') → "hallo")ExchangeAt(index, count, replacement)- Replace substring range (e.g., "hello".ExchangeAt(1, 2, "ay") → "haylo")Repeat(count)- Repeat string N times (e.g., "ab".Repeat(3) → "ababab")RemoveFirst(count)/RemoveLast(count)- Remove N characters from start/end (e.g., "hello".RemoveFirst(2) → "llo")RemoveAtStart(what)/RemoveAtEnd(what)- Remove specific prefix/suffix (e.g., "hello".RemoveAtEnd("lo") → "hel")SubString(start, end)- Alternative substring using end index instead of lengthLeft(count)/Right(count)- Get N leftmost/rightmost characters safely (returns shorter if string too short)Split(int)/Split(Regex)- Split into fixed-size chunks or by regex pattern
Replace Operations
Flexible string replacement methods
ReplaceFirst(what, replacement)- Replace only first occurrence (e.g., "hello".ReplaceFirst("l", "L") → "heLlo")ReplaceLast(what, replacement)- Replace only last occurrence (e.g., "hello".ReplaceLast("l", "L") → "helLo")MultipleReplace(dict)- Replace multiple patterns at once (e.g., "a b c".MultipleReplace({{"a","x"},{"b","y"}}) → "x y c")MultipleReplace(target, replacements)- Replace target with one of many valuesReplaceRegex(pattern, replacement)- Regex-based replacement with capture groupsReplace()with limits - Limit number of replacements (e.g., Replace("l", "L", maxCount: 1))
StartsWith/EndsWith Operations
Comprehensive prefix and suffix checking with flexible comparison
StartsWith()- Check if string starts with char/string (supports StringComparison)StartsNotWith()- Negated prefix checkStartsWithAny()- Check if starts with any of multiple values (e.g., "hello".StartsWithAny("hi", "he") → true)StartsNotWithAny()- Check if doesn't start with any valueEndsWith()- Check if string ends with char/string (supports StringComparison)EndsNotWith()- Negated suffix checkEndsWithAny()- Check if ends with any of multiple valuesEndsNotWithAny()- Check if doesn't end with any value
Contains & Search Operations
Advanced substring searching and set membership
Contains()- Check if string contains substring (with StringComparison support)ContainsNot()- Check if string doesn't contain substringContainsAll()- Check if contains all of multiple substrings (e.g., "hello world".ContainsAll("hello", "world") → true)ContainsAny()- Check if contains any of multiple substringsContainsNotAny()- Check if doesn't contain any of multiple substringsIndexOf()variants - Enhanced searching with culture/comparison optionsIsAnyOf()- Check if string equals any in a set (e.g., "cat".IsAnyOf("dog", "cat", "bird") → true)IsNotAnyOf()- Check if string doesn't equal any in a set
Null & State Checking
Comprehensive null, empty, and whitespace validation
IsNull()/IsNotNull()- Check if string is nullIsEmpty()/IsNotEmpty()- Check if string is "" (empty but not null)IsNullOrEmpty()/IsNotNullOrEmpty()- Combined null or empty checkIsNullOrWhiteSpace()/IsNotNullOrWhiteSpace()- Check for null, empty, or only whitespaceIsWhiteSpace()/IsNotWhiteSpace()- Check if string contains only whitespace (but not empty)DefaultIf()/DefaultIfEmpty()/DefaultIfNullOrEmpty()- Return default value based on state (e.g., "".DefaultIfEmpty("N/A") → "N/A")
Text Processing & Analysis
Linguistic analysis and text processing utilities
SanitizeForFileName()- Remove/replace invalid filesystem characters (e.g., "file:name".SanitizeForFileName() → "file_name")GetSoundexRepresentation()- Phonetic encoding for fuzzy matching (e.g., "Robert".GetSoundexRepresentation() → "R163")TextAnalysis()- Comprehensive text analysis returning:- Word Count - Total words and unique words
- Sentence Count - Number of sentences (handles abbreviations)
- Syllable Count - Syllables per word (multi-language support)
- Word Frequency - Histogram of word occurrences
- Readability Metrics - Flesch-Kincaid, Gunning Fog, etc.
Truncate()- Shorten text with ellipsis (e.g., "Long text".Truncate(8) → "Long te...")WordWrap()- Wrap text to specified line widthRemoveDiacritics()- Remove accents and diacritical marks (e.g., "café" → "cafe")
Cryptography & Hashing (2 methods)
ComputeHash<TAlgorithm>()- Generic hash computation with any HashAlgorithmComputeHash(hashAlgorithm)- Hash with specific algorithm instance
Regular Expressions (8+ methods)
IsMatch(regex)/IsNotMatch(regex)- Pattern matching with Regex objectsIsMatch(pattern, options)/IsNotMatch(pattern, options)- Pattern matching with string patternsMatches(pattern, options)- Get all pattern matchesMatchGroups(pattern, options)- Extract regex capture groupsAsRegularExpression(options)- Convert string to compiled Regex
Advanced Formatting (8+ methods)
FormatWith(parameters)- Enhanced string.Format with better error handlingFormatWithEx(fields, comparer)- Template-based formatting with custom field resolutionFormatWithEx(KeyValuePair<string, object>[])- Formatting with key-value pairsFormatWithEx(IDictionary<string, string>)- Dictionary-based formattingFormatWithObject<T>(object)- Format using object properties via reflection
Type-Safe Parsing (400+ methods)
Generated via T4 templates for 15 data types: Float, Double, Decimal, Byte, SByte, UInt16, Int16, UInt32, Int32, UInt64, Int64, TimeSpan, DateTime, Boolean, Color
Each type provides:
Parse{Type}()- Basic parsingParse{Type}(IFormatProvider/NumberStyles)- Culture-aware parsingTryParse{Type}(out result)- Safe parsing variantsParse{Type}OrDefault(defaultValue)- Parsing with fallback valuesParse{Type}OrNull()- Nullable parsing for value types- ReadOnlySpan<char> support for zero-allocation parsing
Database & Special Formats (3+ methods)
ToLinq2SqlConnectionString()- Convert to LINQ-to-SQL connection formatMsSqlIdentifierEscape()- Escape SQL Server identifiers- Line breaking and special format utilities
Character Access (4 methods)
First()/FirstOrDefault(defaultChar)- Get first character safelyLast()/LastOrDefault(defaultChar)- Get last character safely
Modern .NET Features (5+ methods)
CopyTo(Span<char> target)- Copy to span for zero-allocation scenarios- Span-based operations with
ReadOnlySpan<char>support - Performance-optimized implementations using
stackallocfor small strings
Enum Extensions (Enum)
Enhanced enum operations with attribute support
- Attribute Access -
GetFieldDescription<T>(),GetFieldDisplayName<T>(),GetFieldAttribute<T,TAttr>()- Retrieve attributes from enum values - String Conversion -
ToString<T,TAttr>(),ToStringOrDefault<T,TAttr>()- Convert enum to string using attribute values - Parsing -
ParseEnum<T,TAttr>(),ParseEnumOrDefault<T,TAttr>()- Parse strings to enum values via attributes - Flag Operations -
HasFlag(),SetFlag(),ClearFlag(),ToggleFlag()- Manipulate flag enums - Enumeration -
GetValues(),GetNames(),GetFlags()- Retrieve all enum values/names/flags
Random Extensions (Random)
Advanced random generation with type-specific methods
- Password Generation -
GeneratePassword()- Generate secure passwords with customizable rules - Boolean -
GetBoolean()- Random true/false values - Dice Rolling -
RollADice()- Simulate dice rolls (default 6-sided) - Type-Specific Generators -
GetValueFor<T>()- Generate random value for any supported type - Integer Ranges -
GetInt8(),GetInt16(),GetInt32(),GetInt64(),GetUInt8(),GetUInt16(),GetUInt32(),GetUInt64()- Full range random integers - Floating-Point -
GetFloat(),GetDouble(),GetDecimal()- Random floating-point with control over special values (NaN, Infinity) - Characters -
GetChar()- Random character with filters (ASCII, control chars, whitespace, surrogates) - Strings -
GetString()- Random strings with length constraints - Ranged Double -
NextDouble(min, max)- Random double within specified range
Console Extensions (Console)
Enhanced console I/O operations
- Colored Output -
WriteLineColored(),WriteColored()- Write text with foreground/background colors - Formatted Output -
WriteLineFormatted()- Write formatted text with color codes - Input -
ReadLineSecure()- Read input without echoing (for passwords) - Progress Indicators -
WriteProgress()- Display progress bars and indicators
Convert Extensions
Additional encoding and conversion utilities
- Base91 Encoding -
ToBase91String(),FromBase91String()- Efficient base91 encoding (more compact than base64) - Quoted-Printable -
ToQuotedPrintableString(),FromQuotedPrintableString()- Email-compatible encoding
Uri Extensions (Uri)
Web resource access and manipulation
- Content Retrieval -
ReadAllText(),ReadAllBytes()- Download content from URIs - Async Operations -
ReadAllTextTaskAsync(),ReadAllBytesTaskAsync()- Asynchronous download methods - File Download -
DownloadToFile()- Download content directly to file - URI Manipulation -
BaseUri(),Path()- Construct and manipulate URIs - Response Handling -
GetResponseUri()- Get final URI after redirects - HTTP Support - Custom headers, POST data, retry logic for all methods
StringBuilder Extensions (StringBuilder)
StringBuilder manipulation and utilities
- Character Operations -
Append()overloads for various types - Line Operations -
AppendLine()variants with formatting - Conditional Append -
AppendIf(),AppendLineIf()- Conditional appending - Modification -
Replace(),Remove(),Insert()- Enhanced manipulation methods - Inspection -
Contains(),StartsWith(),EndsWith()- Content checking
Regex Extensions (Regex, Match)
Regular expression utilities
- Match Operations -
MatchAll(),GetMatches()- Retrieve all matches - Replace Operations -
ReplaceWith()- Functional replacement patterns - Testing -
IsMatch(),HasMatch()- Pattern testing - Group Access -
GetGroupValue(),GetGroupValues()- Extract capture groups - Match Extensions -
GetValue(),GetValues()- Value extraction from Match objects
CultureInfo Extensions (CultureInfo)
Culture and localization utilities
- Culture Operations -
IsNeutral(),IsSpecific()- Culture type checks - Hierarchy -
GetParent(),GetAncestors()- Culture hierarchy navigation - Comparison -
IsAncestorOf(),IsDescendantOf()- Culture relationship checks
Collection Extensions (Collections, Generic Collections, Concurrent Collections)
Methods for collection operations including dictionaries, lists, and concurrent collections
Dictionary Extensions (IDictionary<TKey, TValue>)
Dictionary operations with thread-safety support
AddRange(keyValuePairs)- Bulk addition operationsGetValueOrDefault(key, defaultValue)- Safe value retrievalGetValueOrNull(key)- Null-safe value retrievalAddOrUpdate(key, value)- Upsert operationsGetOrAdd(key, valueFactory)- Lazy value additionTryAdd(key, value)/TryRemove(key, out value)- Safe modificationsTryUpdate(key, newValue, comparisonValue)- Conditional updatesCompareTo(other, keyComparer, valueComparer)- Dictionary comparison
Generic Collection Extensions
Extensions for List, HashSet, Queue, Stack, LinkedList, and related types
- List Extensions - TrySetFirst/Last/Item, RemoveEvery, Swap, Shuffle, Permutate, BinarySearchIndex variants
- HashSet Extensions - CompareTo, ContainsNot, TryAdd, TryRemove
- Queue Extensions - PullTo variants, PullAll, Pull, AddRange, Add, Fetch, TryDequeue
- Stack Extensions - PullTo variants, PullAll, Pull, Exchange, Invert, AddRange, Add, Fetch
- LinkedList Extensions - Navigation and manipulation
- Collection Extensions - General ICollection<T> utilities
- Enumerable Extensions - T4-generated LINQ-style operations
- KeyValuePair Extensions - Reverse key-value pairs
Concurrent Collection Extensions
Thread-safe collection operations for concurrent scenarios
- ConcurrentDictionary Extensions - Atomic operations
- ConcurrentQueue Extensions - Queue operations with bulk processing
- ConcurrentStack Extensions - Stack operations with safety guarantees
Specialized Collection Extensions
- StringDictionary Extensions - String-specific dictionary operations
- StringCollection Extensions - String collection utilities
- BitArray Extensions - Bit manipulation operations
- LINQ Extensions - IQueryable enhancements
- ObjectModel Collection Extensions - Observable collections
File System Extensions
File system operations including FileInfo, DirectoryInfo, and Stream extensions
FileInfo Extensions (FileInfo)
File operations with async support
File Operations
EnableCompression()/TryEnableCompression()- NTFS compressionGetTypeDescription()- File type identificationRenameTo(newName)- Safe file renamingChangeExtension(newExtension)- Extension modificationMoveTo(destination, timeout, overwrite)- Enhanced move with options
Async Operations
CopyToAsync(target, cancellationToken, overwrite)- Async file copying- Enhanced async operations with progress reporting and cancellation
Hash & Integrity
ComputeHash<THashAlgorithm>()- Generic hash computationComputeHash(provider, blockSize)- Custom hash with block sizeComputeSHA512Hash()/ComputeSHA384Hash()/ etc. - Specific algorithms
DirectoryInfo Extensions (DirectoryInfo)
Directory operations and navigation
Directory Management
RenameTo(newName)- Directory renamingClear()- Clear directory contentsGetSize()- Calculate total directory sizeGetRealPath()- Resolve symbolic linksTryCreate(recursive)/TryDelete(recursive)- Safe operations
Navigation & Queries
Directory(subdirectory, ignoreCase)- Navigate to subdirectoriesFile(filePath, ignoreCase)- Get files within directoryGetOrAddDirectory(name)- Get or create subdirectoryHasDirectory(searchPattern, option)/HasFile(searchPattern, option)- Content checksContainsFile(fileName, option)/ContainsDirectory(directoryName, option)- Specific searchesExistsAndHasFiles(fileMask)- Existence and content verification
Utilities
GetTempFile(extension)- Generate temporary filesTryCreateFile(fileName, attributes)- Safe file creationTrySetLastWriteTimeUtc()/TrySetCreationTimeUtc()/TrySetAttributes()- Safe attribute management
Stream Extensions (Stream)
Stream operations for various data types
- Primitive I/O Operations - Read/Write for primitive types (bool, byte, short, int, long, float, double, decimal)
- Endianness Support - Big-endian and little-endian operations
- String Operations - Length-prefixed, zero-terminated, and fixed-length strings
- Struct Operations - Struct serialization, positioned reads with seek origin support
- Async Operations - Async/await support for positioned operations
- Stream Analysis - End-of-stream detection, stream-to-array conversion
- Buffer Management - Buffer management using thread-static and shared buffers
BinaryReader Extensions (BinaryReader)
Binary reading utilities
- Extended Reads -
ReadBytes(),ReadString()with various encodings - Positioned Reading - Read at specific positions without seeking
- Array Reading - Read arrays of primitives efficiently
TextReader Extensions (TextReader)
Text reading utilities
- Line Operations -
ReadLines(),ReadAllLines()- Enumerate or read all lines - Buffered Reading -
ReadBlock()- Read fixed-size blocks - Async Operations - Async versions of read operations
DriveInfo Extensions (DriveInfo)
Drive information and management
- Drive Operations -
GetFreeSpace(),GetTotalSpace()- Space queries - Drive Checks -
IsReady(),IsFixed(),IsRemovable()- Drive type checking - Volume Information -
GetVolumeLabel(),SetVolumeLabel()- Label management
Volume Extensions (Volume)
System volume enumeration and management
- Volume Discovery - Enumerate all system volumes
- Mount Point Operations - Get/set volume mount points
- Volume Properties - Access volume-specific information
Path & FileSystem Extensions
Path manipulation and file system utilities
- Temporary Resource Management - Temporary file/directory creation with auto-cleanup
- Cross-Platform Support - Multi-OS temporary directory resolution
- UNC Path Operations - Network path parsing and manipulation
- Relative Path Calculation - Relative paths between file system objects
Math & Numeric Extensions
Mathematical operations for numeric types
Bit Manipulation Extensions
Bitwise operations with hardware intrinsics support
LowerHalf()/UpperHalf()- Extract lower/upper bit portions from multi-byte typesRotateLeft(count)/RotateRight(count)- Bitwise rotation for all integer typesTrailingZeroCount()/LeadingZeroCount()- Count trailing/leading zeros with SIMD optimizationTrailingOneCount()/LeadingOneCount()- Count trailing/leading onesCountSetBits()/CountUnsetBits()- Population count operations (Brian Kernighan's algorithm)Parity()- Check if number of set bits is even/oddReverseBits()- Reverse bit order using lookup tablesParallelBitExtract(mask)- Extract bits based on bitmaskDeinterleaveBits()/PairwiseDeinterleaveBits()- Bit deinterleaving operationsFlipBit()/GetBit()/SetBit()/ClearBit()- Individual bit manipulationIsPowerOfTwo()- Fast power-of-2 testing using bitwise AND tricksAnd()/Or()/Xor()/Not()/Nand()/Nor()- Bitwise logical operations
Advanced Mathematical Functions
Mathematical functions with precision implementations
Standard Math Functions:
Pow(exponent)/Sqrt()/Cbrt()- Power, square root, cube rootFloor()/Ceiling()/Truncate()- Rounding operations with MidpointRounding supportRound(decimals, midpointRounding)- Advanced rounding with banker's roundingAbs()/Sign()- Absolute value and sign extractionLogN(base)/Log()/Log10()/Log2()- Logarithmic functionsExp()- Exponential function with Taylor series for decimal precision
Trigonometric Functions:
Sin()/Cos()/Tan()- Basic trigonometric functionsSinh()/Cosh()/Tanh()- Hyperbolic functionsCot()/Coth()- Cotangent and hyperbolic cotangentCsc()/Csch()- Cosecant and hyperbolic cosecantSec()/Sech()- Secant and hyperbolic secantAsin()/Acos()/Atan()- Inverse trigonometric functionsArsinh()/Arcosh()/Artanh()- Inverse hyperbolic functionsAcot()/Asec()/Acsc()/Arcoth()/Arsech()/Arcsch()- Extended inverse functions
Arithmetic Operations
Operations for numeric types: byte, sbyte, short, ushort, int, uint, long, ulong, float, double, decimal
Basic Arithmetic:
Add()/Subtract()/MultipliedWith()/DividedBy()- Functional-style arithmeticSquared()/Cubed()- Common power operations with overflow checkingAverage(other)- Precise average calculation avoiding overflowFusedMultiplyAdd()/FusedMultiplySubtract()- Hardware-accelerated fused operationsFusedDivideAdd()/FusedDivideSubtract()- Custom fused divide operations
Shift Operations (Integer Types):
ArithmeticShiftLeft()/ArithmeticShiftRight()- Sign-preserving bit shiftsLogicalShiftLeft()/LogicalShiftRight()- Zero-fill bit shifts
Comparison & Range Operations
Comparison operations for numeric types
Value State Checks:
IsZero()/IsNotZero()- Zero comparison with epsilon for floating-pointIsPositive()/IsNegative()/IsPositiveOrZero()/IsNegativeOrZero()- Sign checkingIsEven()/IsOdd()- Parity checking using bitwise ANDIsAbove()/IsBelow()/IsAboveOrEqual()/IsBelowOrEqual()- Relational comparisonsIsBetween()/IsInRange()- Range validation with inclusive/exclusive boundsIsIn()/IsNotIn()- Set membership testing
Floating-Point Specific:
IsNaN()/IsInfinity()/IsPositiveInfinity()/IsNegativeInfinity()- IEEE 754 special value detectionIsNumeric()/IsNonNumeric()- Validity checking for calculationsReciprocalEstimate()- Fast reciprocal approximation using hardware instructions
Type-Safe Unsigned Wrappers
UnsignedFloat, UnsignedDouble, UnsignedDecimal - compile-time negative value prevention
Arithmetic Support:
- Standard operators (+, -, *, /, %) with overflow checking
- Comparison operators
- Implicit conversions from unsigned integer types
- Explicit conversions from signed types with validation
IComparable,IConvertible,IFormattableinterface implementationsISpanParsable,ISpanFormattablesupport for .NET 7+
Mathematical Operations:
- Standard math functions adapted for unsigned constraints
- Handling for operations that could produce negative results
Utility Extensions
Operations:
Min()/Max()- Min/max operationsBits()- IEEE 754 bit representation for floating-point typesEqu()- Equality comparison with configurable epsilon
Repetition Extensions:
For integer types (byte through long)
Times(Action)- Execute action N timesTimes(Action<T>)- Execute action N times with index parameterTimes(string)- Repeat string N timesTimes(char)- Repeat character N times
Performance Features
- Hardware intrinsics integration (SIMD, FMA, etc.)
- Aggressive inlining using
MethodImplOptions.AggressiveInlining - High-precision algorithms (Taylor series, Newton-Raphson methods)
- Overflow detection for safe arithmetic
- Epsilon-based comparisons for floating-point operations
- SIMD optimizations where hardware supports it
- Lookup tables for bit manipulation operations
- Branch reduction using bitwise operations
DateTime Extensions (DateTime)
Comprehensive date and time operations
- Day Boundaries -
StartOfDay(),EndOfDay()- Get start/end of current day - Week Operations -
AddWeeks(),DateOfDayOfCurrentWeek(),StartOfWeek(),DayInCurrentWeek()- Week-based calculations - Month Boundaries -
FirstDayOfMonth(),LastDayOfMonth()- Get first/last day of month - Year Boundaries -
FirstDayOfYear(),LastDayOfYear()- Get first/last day of year - Comparison -
Max(),Min()- Compare and return min/max dates - Date Ranges -
DaysTill()- Enumerate days between dates - Sequence Generation -
Sequence(start, end, step),InfiniteSequence(start, step)- Generate finite or infinite sequences of DateTime values with a TimeSpan step - Subtraction Methods -
SubstractTicks(),SubstractMilliseconds(),SubstractSeconds(),SubstractMinutes(),SubstractHours(),SubstractDays()- Subtraction alternatives to Add with negative values - Formatting - Culture-aware formatting and parsing
TimeSpan Extensions (TimeSpan)
Duration calculations and utilities
- Arithmetic -
Multiply(),Divide()- Scalar multiplication and division - Comparison -
IsPositive(),IsNegative(),IsZero()- Duration state checks - Formatting -
ToHumanReadable()- Convert to friendly format (e.g., "2 hours, 30 minutes") - Conversion -
TotalWeeks()- Get total weeks as double
Type Extensions (Type)
Type reflection and inspection utilities
- Type Constants -
TypeVoid,TypeBool,TypeChar,TypeString, etc. - Static type references - Castability -
IsCastableTo()- Check if type can be cast to another - Hierarchy -
GetBaseTypes(),GetInterfaces()- Enumerate type hierarchy - Attributes -
HasAttribute<T>(),GetAttribute<T>()- Attribute presence and retrieval - Type Checks -
IsNumeric(),IsNullable(),IsEnum(),IsDelegate()- Common type category checks - Generic Support -
GetGenericArguments(),IsGenericType()- Generic type inspection - Default Values -
GetDefault()- Get default value for type
BitConverter Extensions
Enhanced byte array conversion
- Primitive Types -
ToSByte(),ToByte(),ToShort(),ToChar()- Convert byte arrays to primitives - Nullable Support -
ToNSByte(),ToNByte(),ToNChar()- Convert to nullable primitives with null marker - Reverse Operations -
GetBytes()- Convert primitives (including nullables) to byte arrays - Endianness Control - Methods for both big-endian and little-endian conversions
Threading & Task Extensions
Concurrent programming and synchronization utilities
Task Management Extensions
DeferredTask- Lazy task execution with dependency managementScheduledTask- Scheduled task executionSequential- Sequential task processor with ordering guaranteesTask- Task utilitiesFuture<T>- Future/promise pattern implementation
Interlocked Extensions
Atomic operations with enum support and flag manipulation
- Standard Atomic Operations - Interlocked operations
- T4-Generated Enum Operations - Type-safe atomic operations for enums:
- Flag operations (set, clear, toggle, test atomically)
- Enum arithmetic (add, subtract, increment, decrement)
- Conditional updates (CompareExchange with strong typing)
- Read operations (atomic reads with memory barriers)
Synchronization Primitives
Synchronization with thread-safety features
SemaphoreSlimExtensions - Semaphore operationsManualResetEventExtensions - Event signaling utilitiesThreadExtensions - Thread management and utilitiesTimerExtensions - Timer operations
Threading Utilities
CallOnTimeout- Timeout-based callback executionEvent- Event signaling with multiple listenersHighPrecisionTimer- High-resolution timing
Diagnostics Extensions
Process and performance monitoring utilities
Process Extensions (Process)
- Process Management -
Kill(),WaitForExit()- Process lifecycle management - Priority -
SetPriority(),GetPriority()- Process priority management - Information -
GetCommandLine(),GetParent()- Process information retrieval
ProcessStartInfo Extensions (ProcessStartInfo)
- Fluent Configuration - Fluent API for configuring process start parameters
- Argument Building -
AddArgument(),AddArguments()- Argument list building - Environment -
AddEnvironmentVariable()- Environment variable management
Stopwatch Extensions (Stopwatch)
- Measurement -
Measure()- Measure execution time of actions - Reset Operations -
RestartWith()- Reset and start with new measurement - Timing Utilities -
GetElapsedAndRestart()- Get elapsed time and restart
Reflection Extensions
Advanced reflection utilities for types and metadata
Assembly Extensions (Assembly)
- Attribute Access -
GetCustomAttribute<T>(),GetCustomAttributes<T>(),HasAttribute<T>()- Retrieve assembly-level attributes - Type Discovery -
GetLoadableTypes(),GetTypesImplementing<T>()- Find types within assemblies - Version Info -
GetFileVersion(),GetProductVersion()- Retrieve version information
MethodInfo Extensions (MethodInfo)
- Invocation -
Invoke<T>()- Type-safe method invocation - Signature Matching -
MatchesSignature()- Compare method signatures - Extension Method Detection -
IsExtensionMethod()- Check if method is an extension method - Attribute Retrieval -
GetCustomAttribute<T>()- Get method attributes
PropertyInfo Extensions (PropertyInfo)
- Value Access -
GetValue<T>(),SetValue<T>()- Type-safe property access - Attribute Retrieval -
GetCustomAttribute<T>()- Get property attributes - Backing Field Access -
GetBackingField()- Access compiler-generated backing fields
FieldInfo Extensions (FieldInfo)
- Value Access -
GetValue<T>(),SetValue<T>()- Type-safe field access - Attribute Retrieval -
GetCustomAttribute<T>()- Get field attributes
ParameterInfo Extensions (ParameterInfo)
- Attribute Access -
GetCustomAttribute<T>(),HasAttribute<T>()- Retrieve parameter attributes - Default Values -
GetDefaultValue<T>()- Get parameter default value
Networking Extensions
Network-related utilities and operations
IPAddress Extensions (IPAddress)
- Address Manipulation -
IsInRange(),IsPrivate(),IsLoopback()- IP address classification - Subnet Operations -
GetNetworkAddress(),GetBroadcastAddress()- Calculate network addresses - Conversion -
ToUInt32(),ToBytes()- Convert IP addresses to numeric formats
WebHeaderCollection Extensions (WebHeaderCollection)
- Header Access - Simplified access to common HTTP headers
- Bulk Operations -
AddRange(),SetRange()- Add/set multiple headers at once
Security Extensions
Cryptographic and security utilities
HashAlgorithm Extensions
- File Hashing -
ComputeHash()- Compute file hashes - Stream Hashing -
ComputeHash()- Compute stream hashes - String Hashing - Extensions for computing hashes from strings
SecureString Extensions (SecureString)
- Conversion -
ToUnsecureString(),ToByteArray()- Convert SecureString to usable formats - Comparison -
EqualsSecure()- Secure string comparison
LINQ Extensions
Enhanced LINQ operations and queries
IQueryable Extensions (IQueryable<T>)
- Query Building -
Where(),OrderBy(),Select()enhancements - Paging -
Skip(),Take()- Pagination support - Expression Utilities - Expression tree manipulation
Enumerable Extensions (See Collection Extensions)
Comprehensive LINQ-style operations documented in Collections section above
XML Extensions
XML manipulation and querying utilities
XmlNode Extensions (XmlNode)
- Navigation -
GetChildNodes(),GetDescendants()- Node traversal - Query -
SelectNodes(),SelectSingleNode()enhancements - Modification -
AddChild(),RemoveChild()- Node manipulation - Attribute Access -
GetAttribute(),SetAttribute()- Attribute management
XmlAttributeCollection Extensions (XmlAttributeCollection)
- Collection Operations - Enhanced attribute collection manipulation
- Lookup -
ContainsAttribute(),TryGetAttribute()- Attribute retrieval
Data & ComponentModel Extensions
Data binding and database operations
Data Extensions
DataRecord/DataRow/DataTableExtensions - Data operations- LINQ to Data Extensions - Querying utilities
- SQL Client Extensions - Database utilities
ComponentModel Extensions
BindingList/SortableBindingList- Data binding- Property Change Notifications - MVVM support
- Attribute Extensions - Metadata utilities
New Types
Collection Types
Collection implementations for specialized use cases
Array Utilities
ArraySlice<TItem>- Mutable array slice with indexer supportReadOnlyArraySlice<TItem>- Read-only array slice with enumeration
Advanced Collections
BiDictionary<TFirst, TSecond>- Bidirectional dictionary with O(1) reverse lookupDoubleDictionary<TOuter, TInner, TValue>- Two-level nested dictionaryFastLookupTable<TItem>- High-performance lookup table with optimized hashingOrderedDictionary<TKey, TValue>- Dictionary maintaining insertion orderCachedEnumeration<TItem>- Caching enumeration wrapper for expensive operations
Concurrent Collections
ExecutiveQueue<TItem>- Advanced queue with priority and executive featuresConcurrentWorkingBag<T>- Thread-safe working bag with enumeration
Change Tracking System
Comprehensive change detection and tracking
IChangeSet<TItem>- Interface for change tracking operationsChangeSet<TItem>- Complete change tracking implementationChangeType- Enumeration:Added,Removed,Changed,Equal
File Operations Framework
Advanced file comparison and processing
File Comparison
IFileComparer- Base interface for file comparison strategiesITemporaryFileToken- Temporary files with auto-disposalITemporaryDirectoryToken- Temporary directories with auto-disposalBinaryFileComparer- Byte-by-byte binary comparisonFileLengthComparer- Fast length-based comparisonFileSimpleAttributesComparer- Attribute-based comparisonFileCreationTimeComparer- Creation time comparisonFileLastWriteTimeComparer- Last write time comparison
Enhanced I/O
IFileInProgress- Interface for file operation progress trackingFileInProgress- File operation progress implementationCustomTextReader- Enhanced text reader with advanced featuresBufferedStreamEx- Extended buffered stream with performance optimizations
Cryptography & Hashing
Comprehensive hashing algorithms and security utilities
Advanced Hashing
IAdvancedHashAlgorithm- Interface for advanced hashing featuresAdler- Adler-32 checksum algorithmFletcher- Fletcher checksum variants (16/32-bit)JavaHash- Java-compatible string hashingLRC8- 8-bit Longitudinal Redundancy CheckPearson- Pearson hashing algorithmTiger- Tiger hash algorithm (192-bit)Whirlpool- Whirlpool hash algorithm (512-bit)RandomNumberProvider- Enhanced cryptographically secure random generation
Threading & Concurrency
Advanced concurrent programming constructs
Task Management
DeferredTask- Lazy task execution with dependency managementScheduledTask- Cron-like scheduled task executionSequential- Sequential task processor with ordering guarantees
Synchronization Primitives
CallOnTimeout- Timeout-based callback executionEvent- Enhanced event signaling with multiple listenersFuture<T>- Future/promise pattern implementationHighPrecisionTimer- High-resolution timing for performance-critical code
Property & State Management
Advanced property and state management utilities
Smart Properties
FastLazy<T>- High-performance lazy initializationRealtimeProperty<T>- Real-time property with change notificationsSlowProperty<T>- Throttled property updates for expensive operationsIndexedProperty<T>- Property with indexer supportStaticMethodLocal<T>- Static method-local storage
Utility Types
Essential utility types for common programming patterns
Core Utilities
Range- Enhanced range operations and arithmeticSpanEnhancements - Extended span utilities and operations
Validation Framework
Against- Comprehensive parameter validation with performance optimizationAlwaysThrow- Exception throwing utilities with stack trace and inlining optimization
Text Processing
TextAnalyzer- Advanced text analysis with readability metricsReadabilityScoreCalculator- Multiple readability algorithm implementations
Performance Features
Optimizations
- Unsafe Code Blocks - Direct memory manipulation for performance
- SIMD Operations - Vectorized operations using block processing
- Aggressive Inlining - Use of
MethodImplOptions.AggressiveInlining - Stack Allocation -
stackallocfor temporary buffers - Span<T> and Memory<T> - Modern .NET memory management
Memory Efficiency
- Reduced Allocations - Operations designed to avoid unnecessary heap allocations
- Object Pooling - Reusable object patterns where applicable
- Block-based Operations -
Block32,Block64for memory operations - Bounds Check Elimination - Loop construction to help JIT optimize
Installation & Usage
<PackageReference Include="FrameworkExtensions.Corlib" Version="*" />
using System;
using Corlib.Extensions;
// Array operations
var numbers = new[] { 3, 1, 4, 1, 5, 9 };
numbers.QuickSort();
var slice = numbers.Slice(1, 3);
// String operations
var text = "hello_world";
var pascalCase = text.ToPascalCase(); // "HelloWorld"
var hash = text.ComputeHash<SHA256>();
// Collection operations
var dict = new Dictionary<string, int>();
dict.AddOrUpdate("key", 42);
var value = dict.GetValueOrDefault("missing", 0);
// File operations
var file = new FileInfo("data.txt");
file.EnableCompression();
var hash = file.ComputeSHA256Hash();
Target Frameworks
Multi-targeting support:
- .NET Framework:
net35,net40,net45,net48 - .NET Standard:
netstandard2.0 - .NET Core/5+:
netcoreapp3.1,net6.0,net7.0,net8.0,net9.0
Library Statistics
Overview
- 3,300+ Extension Methods across common .NET types
- 50+ .NET Types Extended covering major framework types
- 15+ Data Types with type-safe parsing support
- Multiple .NET Versions from .NET 3.5 to .NET 9.0
Technical Features
- Hardware Intrinsics - CPU-specific optimizations (SIMD, FMA, etc.)
- Unsafe Code Optimization - Direct memory manipulation where beneficial
- T4 Code Generation - Compile-time code generation
- Aggressive Inlining - Micro-optimizations throughout
- Memory Pool Usage - Reduced garbage collection pressure
- Branch Reduction - Conditional logic using bitwise operations
Design Principles
- Thread-Safe Operations - Atomic operations and concurrent collection support
- Error Handling - Validation with meaningful error messages
- Globalization Support - Cultural awareness for international applications
- Backwards Compatibility - Supports legacy .NET Framework applications
- Additive API Design - No breaking changes philosophy
Testing & Quality
- 600+ Unit Tests with coverage metrics
- Performance Benchmarks for critical operations
- Cross-Platform CI/CD on Windows, Linux, and macOS
- Memory Leak Testing for allocation-heavy operations
- Thread Safety Testing for concurrent operations
Contributing
See CONTRIBUTING.md for detailed guidelines on:
- Code style and conventions
- Performance requirements
- Testing categories and patterns
- Architecture principles
License
LGPL-3.0-or-later - Use freely, contribute back improvements.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 is compatible. 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 is compatible. 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 is compatible. 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 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 | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 is compatible. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net35 is compatible. net40 is compatible. net403 was computed. net45 is compatible. net451 was computed. net452 was computed. net46 was computed. net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 is compatible. 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. |
-
.NETCoreApp 3.1
- FrameworkExtensions.Backports (>= 1.0.0.212)
- System.Reflection.Emit.Lightweight (>= 4.7.0)
-
.NETFramework 3.5
- FrameworkExtensions.Backports (>= 1.0.0.212)
-
.NETFramework 4.0
- FrameworkExtensions.Backports (>= 1.0.0.212)
-
.NETFramework 4.5
- FrameworkExtensions.Backports (>= 1.0.0.212)
-
.NETFramework 4.8
- FrameworkExtensions.Backports (>= 1.0.0.212)
-
.NETStandard 2.0
- FrameworkExtensions.Backports (>= 1.0.0.212)
- System.Reflection.Emit.Lightweight (>= 4.7.0)
-
net6.0
- FrameworkExtensions.Backports (>= 1.0.0.212)
- System.Reflection.Emit.Lightweight (>= 4.7.0)
-
net7.0
- FrameworkExtensions.Backports (>= 1.0.0.212)
- System.Reflection.Emit.Lightweight (>= 4.7.0)
-
net8.0
- FrameworkExtensions.Backports (>= 1.0.0.212)
- System.Reflection.Emit.Lightweight (>= 4.7.0)
-
net9.0
- FrameworkExtensions.Backports (>= 1.0.0.212)
- System.Reflection.Emit.Lightweight (>= 4.7.0)
NuGet packages (3)
Showing the top 3 NuGet packages that depend on FrameworkExtensions.Corlib:
| Package | Downloads |
|---|---|
|
FrameworkExtensions.System.Windows.Forms
Extensions to WindowsForms. |
|
|
FrameworkExtensions.DirectoryServices
Extensions to DirectoryServices. |
|
|
Hawkynt.RandomNumberGenerators
This package provides various implementations of random number generators. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.0.2.599 | 189 | 3/2/2026 |
| 1.0.2.597 | 113 | 2/9/2026 |
| 1.0.2.592 | 138 | 2/2/2026 |
| 1.0.2.582 | 116 | 1/26/2026 |
| 1.0.2.573 | 118 | 1/19/2026 |
| 1.0.2.570 | 118 | 1/12/2026 |
| 1.0.2.568 | 123 | 1/5/2026 |
| 1.0.2.567 | 110 | 12/29/2025 |
| 1.0.2.565 | 196 | 12/22/2025 |
| 1.0.2.555 | 293 | 12/15/2025 |
| 1.0.2.549 | 379 | 11/17/2025 |
| 1.0.2.547 | 223 | 9/29/2025 |
| 1.0.2.543 | 270 | 9/22/2025 |
| 1.0.2.538 | 338 | 9/16/2025 |
| 1.0.2.537 | 556 | 8/18/2025 |
| 1.0.2.535 | 230 | 8/11/2025 |
| 1.0.2.527 | 191 | 8/4/2025 |
| 1.0.2.504 | 373 | 7/21/2025 |
| 1.0.2.499 | 371 | 7/7/2025 |
| 1.0.2.492 | 205 | 6/23/2025 |