GMana.Extensions
0.0.6
dotnet add package GMana.Extensions --version 0.0.6
NuGet\Install-Package GMana.Extensions -Version 0.0.6
<PackageReference Include="GMana.Extensions" Version="0.0.6" />
<PackageVersion Include="GMana.Extensions" Version="0.0.6" />
<PackageReference Include="GMana.Extensions" />
paket add GMana.Extensions --version 0.0.6
#r "nuget: GMana.Extensions, 0.0.6"
#:package GMana.Extensions@0.0.6
#addin nuget:?package=GMana.Extensions&version=0.0.6
#tool nuget:?package=GMana.Extensions&version=0.0.6
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
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
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 validationIsVowel()
,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 checksTruncate()
- 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 fallbackRemoveAll()
- Bulk key removalMerge()
- 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 introspectionIsDefined<T>()
- Enum value validationTryParse<T>()
,ParseOrDefault<T>()
- Safe enum parsingGetUnderlyingType()
,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 longIsPositive()
,IsNegative()
- Sign checks for int and doubleClamp()
- 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
usesRandom.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
andTryParseByteSize
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
- Follow the established code style (enforced by EditorConfig)
- Add comprehensive XML documentation for all public methods
- Include unit tests for new functionality
- Ensure thread safety for all operations
- Maintain backward compatibility
π License
MIT License - see LICENSE file for details.
π Links
- Repository: https://github.com/sun-sreng/c#-gmana-extensions
- Issues: https://github.com/sun-sreng/c#-gmana-extensions/issues
- Documentation: See XML documentation in source code
Product | Versions 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. |
-
net9.0
- GMana.Utils (>= 0.0.11)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.