Toolbox.Utilities
1.0.1
dotnet add package Toolbox.Utilities --version 1.0.1
NuGet\Install-Package Toolbox.Utilities -Version 1.0.1
<PackageReference Include="Toolbox.Utilities" Version="1.0.1" />
<PackageVersion Include="Toolbox.Utilities" Version="1.0.1" />
<PackageReference Include="Toolbox.Utilities" />
paket add Toolbox.Utilities --version 1.0.1
#r "nuget: Toolbox.Utilities, 1.0.1"
#:package Toolbox.Utilities@1.0.1
#addin nuget:?package=Toolbox.Utilities&version=1.0.1
#tool nuget:?package=Toolbox.Utilities&version=1.0.1
Toolbox.Utilities - Essential Utility Functions
A lightweight .NET 9 library providing essential utility functions and extension methods for collections, dates, and enumerations. Designed for high performance and modern C# development.
Overview
Toolbox.Utilities is a focused collection of extension methods and utility functions that enhance the .NET base class library with commonly needed functionality. Built for personal use, it emphasizes clean code, performance, and modern C# patterns with .NET 9 features.
Features
- Collection Extensions: Enhanced collection manipulation with fluent interfaces
- Date Utilities: ISO 8601 compliant date calculations and manipulations
- Enum Extensions: Rich enum metadata retrieval with description support
- High Performance: Optimized implementations with minimal allocations
- Modern C#: Built for .NET 9 with nullable reference types and implicit usings
- Zero Dependencies: Lightweight with no external dependencies
- Well Documented: Comprehensive XML documentation with practical examples
Installation
This is a personal NuGet package. Install via:
dotnet add package Toolbox.Utilities
Or via Package Manager Console:
Install-Package Toolbox.Utilities
Requirements
- .NET 9.0
Quick Start
Collection Extensions
using Toolbox.Utilities;
// Add multiple items with fluent chaining
var numbers = new List<int> { 1, 2, 3 };
numbers.AddRange(new[] { 4, 5, 6 }); // [1, 2, 3, 4, 5, 6]
// Fluent method chaining
var result = new List<string>()
.AddRange(new[] { "first", "second" })
.AddRange(new[] { "third", "fourth" });
// Works with any ICollection<T>
var hashSet = new HashSet<int> { 1 };
hashSet.AddRange(new[] { 2, 3, 4 });
Date Utilities
using Toolbox.Utilities;
// Get the Monday of any week (ISO 8601 standard)
var friday = new DateOnly(2024, 3, 15);
var monday = friday.GetMonday(); // Returns Monday, March 11, 2024
var sunday = new DateOnly(2024, 3, 17);
var weekStart = sunday.GetMonday(); // Returns Monday, March 11, 2024
// Useful for weekly grouping and reporting
var today = DateOnly.FromDateTime(DateTime.Today);
var currentWeekStart = today.GetMonday();
Enum Utilities
using System.ComponentModel;
using Toolbox.Utilities;
public enum OrderStatus
{
[Description("Order is being processed")]
Processing,
[Description("Order has been shipped")]
Shipped,
Cancelled // No description - falls back to "Cancelled"
}
// Get user-friendly descriptions
var status = OrderStatus.Processing;
var description = status.GetEnumDescription(); // "Order is being processed"
var cancelled = OrderStatus.Cancelled;
var cancelDesc = cancelled.GetEnumDescription(); // "Cancelled"
API Reference
Collections Class
AddRange<TCol, TItem> Extension Method
Adds the elements of the specified collection to the end of the destination collection with fluent interface support.
public static TCol AddRange<TCol, TItem>(this TCol destination, IEnumerable<TItem> source)
where TCol : ICollection<TItem>
Parameters:
destination
: The collection to which elements will be addedsource
: The collection whose elements should be added
Returns: The original destination collection to enable method chaining
Throws:
ArgumentNullException
: When destination or source is null
Performance Notes:
- Optimized for
List<T>
using the built-inAddRange
method - Falls back to efficient iteration for other
ICollection<T>
types - Supports fluent method chaining without creating intermediate collections
Example:
// Basic usage
var list = new List<int> { 1, 2, 3 };
list.AddRange(new[] { 4, 5, 6 });
// Fluent chaining
var combined = new List<string>()
.AddRange(GetPrimaryItems())
.AddRange(GetSecondaryItems())
.AddRange(new[] { "final" });
// Works with HashSet, Queue, Stack, etc.
var uniqueItems = new HashSet<string> { "existing" };
uniqueItems.AddRange(new[] { "new1", "new2", "existing" }); // Duplicates handled by HashSet
Dates Class
GetMonday Extension Method
Gets the Monday of the week for the specified date, following the ISO 8601 standard where Monday is considered the first day of the week.
public static DateOnly GetMonday(this DateOnly date)
Parameters:
date
: The date for which to find the Monday of the week
Returns: A DateOnly
representing the Monday of the same week. If the input date is already Monday, returns the same date.
Features:
- ISO 8601 compliant (Monday as first day of week)
- Handles all edge cases including Sunday correctly
- Efficient with simple arithmetic operations (O(1) complexity)
- No object allocations or string parsing
Example:
// Various days of the week
var friday = new DateOnly(2024, 3, 15); // Friday
var monday = friday.GetMonday(); // Monday, March 11, 2024
var sunday = new DateOnly(2024, 3, 17); // Sunday
var weekStart = sunday.GetMonday(); // Monday, March 11, 2024
var alreadyMonday = new DateOnly(2024, 3, 11); // Monday
var sameDate = alreadyMonday.GetMonday(); // Monday, March 11, 2024
// Weekly reporting example
var salesData = GetSalesData();
var weeklySales = salesData
.GroupBy(s => s.Date.GetMonday())
.ToDictionary(g => g.Key, g => g.Sum(s => s.Amount));
Enums Class
GetEnumDescription Extension Method
Retrieves the description from the DescriptionAttribute
applied to an enum value, or returns the enum's string representation if no description attribute is found.
public static string GetEnumDescription(this Enum value)
Parameters:
value
: The enum value for which to retrieve the description
Returns: The description text from the DescriptionAttribute
if present, otherwise the result of ToString()
Features:
- Reads
[Description]
attribute using reflection - Falls back gracefully to enum name if no attribute exists
- Handles null field info safely
- Benefits from .NET's internal reflection caching
Example:
public enum Priority
{
[Description("Low priority - can be handled later")]
Low,
[Description("High priority - needs immediate attention")]
High,
Critical // No description attribute
}
// Usage in different scenarios
var priority = Priority.Low;
Console.WriteLine(priority.GetEnumDescription());
// Output: "Low priority - can be handled later"
var critical = Priority.Critical;
Console.WriteLine(critical.GetEnumDescription());
// Output: "Critical"
// UI dropdown binding
var priorityOptions = Enum.GetValues<Priority>()
.Select(p => new { Value = p, Display = p.GetEnumDescription() })
.ToList();
// Logging with friendly names
void LogPriorityChange(Priority newPriority)
{
logger.Info($"Priority set to: {newPriority.GetEnumDescription()}");
}
Advanced Usage Examples
Fluent Collection Building
using Toolbox.Utilities;
// Build configuration from multiple sources
var configuration = new Dictionary<string, string>()
.AddRange(GetDefaultSettings())
.AddRange(GetUserPreferences())
.AddRange(GetEnvironmentVariables());
// Combine data from different repositories
var allProducts = new List<Product>()
.AddRange(GetCachedProducts())
.AddRange(GetDatabaseProducts())
.AddRange(GetRemoteProducts());
// Build notification lists
var recipients = new HashSet<string>()
.AddRange(GetManagerEmails())
.AddRange(GetTeamEmails())
.AddRange(GetStakeholderEmails()); // Duplicates automatically removed
Weekly Date Operations
using Toolbox.Utilities;
// Find all Mondays in a date range
DateOnly startDate = new(2024, 1, 1);
DateOnly endDate = new(2024, 12, 31);
var mondaysIn2024 = new List<DateOnly>();
var current = startDate.GetMonday();
while (current <= endDate)
{
mondaysIn2024.Add(current);
current = current.AddDays(7);
}
// Group transactions by week
var transactions = GetTransactions();
var weeklyTotals = transactions
.GroupBy(t => t.Date.GetMonday())
.Select(g => new
{
WeekStart = g.Key,
Total = g.Sum(t => t.Amount),
Count = g.Count()
})
.OrderBy(w => w.WeekStart)
.ToList();
// Check if date is in current week
bool IsCurrentWeek(DateOnly date)
{
var today = DateOnly.FromDateTime(DateTime.Today);
return date.GetMonday() == today.GetMonday();
}
Enum-Driven Applications
using System.ComponentModel;
using Toolbox.Utilities;
public enum NotificationMethod
{
[Description("Send via email")]
Email,
[Description("Send SMS text message")]
SMS,
[Description("Push notification to mobile app")]
Push,
[Description("Internal system notification")]
Internal
}
// Dynamic UI generation
public class NotificationSettings
{
public List<SelectOption> GetMethodOptions()
{
return Enum.GetValues<NotificationMethod>()
.Select(method => new SelectOption
{
Value = method.ToString(),
Label = method.GetEnumDescription()
})
.ToList();
}
}
// Audit logging with descriptions
public class AuditService
{
public void LogNotificationSent(NotificationMethod method, string recipient)
{
var description = method.GetEnumDescription();
auditLog.Info($"Notification sent: {description} to {recipient}");
}
}
// Report generation
public string GenerateNotificationReport(IEnumerable<Notification> notifications)
{
var methodCounts = notifications
.GroupBy(n => n.Method)
.Select(g => $"{g.Key.GetEnumDescription()}: {g.Count()}")
.ToList();
return $"Notifications sent:\n{string.Join("\n", methodCounts)}";
}
Version History
- 1.0.0: Initial release with Collections, Dates, and Enums utilities
License
MIT License - This project is intended for personal usage.
Author
Guillaume Bodson
This library represents commonly needed utilities extracted from real-world development and optimized for personal workflow efficiency.
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
- No dependencies.
GitHub repositories
This package is not used by any popular GitHub repositories.