GMana.Extensions 0.0.6

dotnet add package GMana.Extensions --version 0.0.6
                    
NuGet\Install-Package GMana.Extensions -Version 0.0.6
                    
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="GMana.Extensions" Version="0.0.6" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="GMana.Extensions" Version="0.0.6" />
                    
Directory.Packages.props
<PackageReference Include="GMana.Extensions" />
                    
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 GMana.Extensions --version 0.0.6
                    
#r "nuget: GMana.Extensions, 0.0.6"
                    
#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 GMana.Extensions@0.0.6
                    
#: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=GMana.Extensions&version=0.0.6
                    
Install as a Cake Addin
#tool nuget:?package=GMana.Extensions&version=0.0.6
                    
Install as a Cake Tool

GMana.Extensions

GMana.Extensions is a comprehensive .NET library that provides a collection of extension methods to enhance functionality for common .NET types, including char, string, IDictionary, Enum, numeric types (int, double, long, decimal), JSON handling, and byte size formatting. These extensions simplify tasks such as string manipulation, dictionary operations, enum attribute retrieval, numeric formatting, JSON serialization, and byte size conversions, with specialized support for Khmer language features.

πŸš€ Features

  • String Extensions: Snake case conversion, Khmer character detection, acronym generation, truncation, and more
  • Numeric Extensions: Rounded formatting with suffixes, ordinal strings, Khmer numerals, mathematical utilities
  • JSON Extensions: Safe serialization/deserialization with error handling and validation
  • Dictionary Extensions: Enhanced operations for adding, retrieving, and merging dictionaries
  • Enum Extensions: Attribute retrieval, description handling, parsing utilities with caching
  • Character Extensions: Khmer Unicode validation, vowel/consonant detection
  • Byte Size Extensions: Human-readable formatting and parsing of file sizes
  • Khmer Language Support: Specialized methods for Khmer numerals, month names, and character validation

πŸ“¦ Installation

  1. Add the Library to Your Project:

    • If GMana.Extensions is a standalone project, add it to your solution via a project reference or include the compiled DLL.

    • If distributed via NuGet (hypothetical), install it using:

      dotnet add package GMana.Extensions
      
  2. Import the Namespace:

    • Add the following using statement to your C# files:

      using GMana.Extensions;
      

πŸ”§ Prerequisites

  • .NET Version: .NET 9.0 or later
  • Dependencies: Relies on standard .NET libraries (System, System.Linq, System.Text, System.Text.Json, System.Reflection, System.ComponentModel, System.Globalization)

πŸ“– Usage

Below are examples demonstrating the key methods for each extension class.

πŸ”€ CharExtensions

Provides methods to check character properties including Khmer Unicode validation.

char c = 'αž€';
bool isKhmer = c.IsKhmer(); // Returns true

char vowel = 'a';
bool isVowel = vowel.IsVowel(); // Returns true
bool isConsonant = vowel.IsConsonant(); // Returns false

char? nullableChar = null;
bool isKhmerNullable = nullableChar.IsKhmer(); // Returns false

New Methods Added:

  • IsDigit(), IsLetter(), IsLetterOrDigit() - Character type validation
  • IsVowel(), IsConsonant() - English vowel/consonant detection

πŸ”§ StringExtensions

Enhanced utilities for string manipulation with improved performance and additional features.

string text = "αž€HelloWorld.txt";
bool hasKhmer = text.ContainsKhmer(); // Returns true
string snakeCase = "HelloWorld.txt".ToSnakeCase(); // Returns "hello_world.txt"
string acronym = "Artificial Intelligence".ToAcronymWithRandomSuffix(); // Returns e.g., "AIXYZ"
string random = StringExtensions.CreateRandomString(5); // Returns e.g., "KLMNO"

// New utility methods
string longText = "This is a very long text that needs truncation";
string truncated = longText.Truncate(20); // Returns "This is a very long..."
bool isEmpty = "".IsNullOrEmpty(); // Returns true
bool isWhitespace = "   ".IsNullOrWhiteSpace(); // Returns true

string url = "https://example.com/";
string cleaned = url.TrimEndString(); // Returns "https://example.com"

New Methods Added:

  • IsNullOrEmpty(), IsNullOrWhiteSpace() - Quick null/empty checks
  • Truncate() - String truncation with customizable suffix
  • Improved error handling and performance optimizations

πŸ“š DictionaryExtensions

Enhanced dictionary operations with additional utility methods.

var dict = new Dictionary<string, object?> { { "key1", "value1" } };
dict.AddIfNotExists("key2", "value2"); // Adds key2
bool added = dict.TryAdd("key1", "newValue"); // Returns false (key exists)
dict.AddOrReplace("key1", "updated"); // Updates key1
object? value = dict.Get("key1"); // Returns "updated"
string? stringValue = dict.Get<string>("key1"); // Returns "updated"

// New utility methods
string defaultValue = dict.GetValueOrDefault("missing", "default"); // Returns "default"
int removedCount = dict.RemoveAll(new[] { "key1", "key2" }); // Returns count of removed items

var sourceDict = new Dictionary<string, object?> { { "newKey", "newValue" } };
dict.Merge(sourceDict); // Merges sourceDict into dict

New Methods Added:

  • GetValueOrDefault() - Safe value retrieval with fallback
  • RemoveAll() - Bulk key removal
  • Merge() - Dictionary merging with options

🏷️ EnumExtensions

Enhanced enum utilities with performance improvements and additional functionality.

public enum Status
{
    [Description("In Progress")]
    Processing,
    Completed
}

Status status = Status.Processing;
string description = status.ToDescription(); // Returns "In Progress" (cached)
string fallback = Status.Completed.ToDescription(); // Returns "Completed"

// New utility methods
Status[] allValues = EnumExtensions.GetValues<Status>(); // Get all enum values
string[] allNames = EnumExtensions.GetNames<Status>(); // Get all enum names
bool isDefined = Status.Processing.IsDefined(); // Returns true
Status parsed = EnumExtensions.ParseOrDefault<Status>("Invalid", Status.Completed); // Returns Status.Completed

int numericValue = status.ToNumericValue<int>(); // Convert to underlying numeric value

New Methods Added:

  • GetValues<T>(), GetNames<T>() - Generic enum introspection
  • IsDefined<T>() - Enum value validation
  • TryParse<T>(), ParseOrDefault<T>() - Safe enum parsing
  • GetUnderlyingType(), ToNumericValue() - Type system utilities
  • Performance caching for ToDescription()

πŸ”’ NumericExtensions

Extended numeric formatting and mathematical utilities with Khmer support.

int num = 1234567;
string rounded = num.ToRoundedString(2); // Returns "1.23M"
string ordinal = 21.ToOrdinalString(); // Returns "21st"
string khmerNum = 129.ToKhmerNumber(); // Returns "៑្៩"
string khmerMonth = 1.ToKhmerMonthName(); // Returns "αž˜αž€αžšαžΆ"

// New utility methods
bool isEven = 42.IsEven(); // Returns true
bool isOdd = 43.IsOdd(); // Returns true
bool isPositive = 10.IsPositive(); // Returns true
bool isNegative = (-5).IsNegative(); // Returns true

int clamped = 150.Clamp(0, 100); // Returns 100
double clampedDouble = 1.5.Clamp(0.0, 1.0); // Returns 1.0

// Support for additional numeric types
long bigNum = 1234567890L;
string bigRounded = bigNum.ToRoundedString(); // Returns "1.23B"
string bigKhmer = bigNum.ToKhmerNumber(); // Returns Khmer numerals

New Methods Added:

  • IsEven(), IsOdd() - Parity checks for int and long
  • IsPositive(), IsNegative() - Sign checks for int and double
  • Clamp() - Value clamping for int and double
  • Extended ToRoundedString() support for long and decimal
  • Extended ToKhmerNumber() support for long
  • Performance optimizations with cached Khmer month array

πŸ“„ JSON Extensions

Comprehensive JSON handling with safety and validation features.

// Basic Usage:
var person = new Person { Name = "John", Age = 30 };

// Serialize to JSON
string json = person.ToJsonString();
string prettyJson = person.ToJsonStringPretty(); // Formatted output

// Deserialize from JSON
Person? result = json.FromJsonString<Person>();

// Safe Operations - won't throw exceptions on invalid JSON
Person defaultPerson = "invalid json".TryFromJsonString<Person>();

// Validate JSON before processing
if (jsonString.IsValidJson())
{
    var data = jsonString.FromJsonString<MyClass>();
}

// Deep cloning via JSON
Person clone = person.DeepClone();

// Custom serialization options
var options = new JsonSerializerOptions { WriteIndented = true };
string customJson = person.ToJsonString(options);

πŸ’Ύ ByteSizeExtensions

Human-readable byte size formatting with culture support.

long bytes = 1234567;
string size = bytes.ToByteSizeString(); // Returns "1.23 MB"
string sizeFr = bytes.ToByteSizeString("N1", new CultureInfo("fr-FR")); // Returns "1,2 MB"
bool parsed = ByteSizeExtensions.TryParseByteSize("1.23 MB", out decimal byteCount); // Returns true, byteCount = 1230000

πŸ‡°πŸ‡­ Khmer Language Support

The library includes comprehensive support for the Khmer language:

  • Khmer Numerals: Convert numbers to Khmer digits (e.g., 129.ToKhmerNumber() β†’ ៑្៩)
  • Khmer Month Names: Retrieve Khmer month names (e.g., 1.ToKhmerMonthName() β†’ αž˜αž€αžšαžΆ)
  • Khmer Character Detection: Check for Khmer characters (e.g., 'αž€'.IsKhmer() β†’ true)
  • Unicode Range Support: Covers both main Khmer block (U+1780–U+17FF) and Khmer Symbols (U+19E0–U+19FF)

⚑ Performance and Thread Safety

  • Thread Safety: All methods are thread-safe. CreateRandomString uses Random.Shared for safe concurrent access
  • Performance Optimizations:
    • Compiled regex patterns for string operations
    • Caching for enum descriptions
    • Pre-allocated StringBuilder capacity
    • Optimized Khmer month lookup using arrays
  • Memory Efficient: Minimal allocations and optimized string operations
  • Localization: ToByteSizeString and TryParseByteSize support culture-specific formatting

πŸ”§ Error Handling

  • Comprehensive Validation: Uses ArgumentNullException.ThrowIfNull consistently
  • Safe Defaults: Invalid inputs return sensible defaults rather than throwing exceptions
  • Exception Documentation: All methods document their exception conditions
  • Robust JSON Handling: JSON methods include safe variants that don't throw on invalid input

πŸ“Š Code Quality

  • Full XML Documentation: All public methods include comprehensive documentation
  • Code Analysis: Enabled with latest analyzers and strict warning treatment
  • EditorConfig: Consistent code style enforcement
  • Modern C# Features: Leverages C# 12+ features and .NET 9 capabilities

🀝 Contributing

  1. Follow the established code style (enforced by EditorConfig)
  2. Add comprehensive XML documentation for all public methods
  3. Include unit tests for new functionality
  4. Ensure thread safety for all operations
  5. Maintain backward compatibility

πŸ“„ License

MIT License - see LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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
0.0.6 145 9/12/2025
0.0.5 176 8/13/2025
0.0.3 298 6/10/2025
0.0.2 159 5/26/2025
0.0.1 149 5/19/2025