### Cloning Source Code Repository Source: https://github.com/danielwertheim/ensure.that/blob/master/README.md To get started with the source code, clone the repository using git. ```bash git clone ... ``` -------------------------------- ### GUID Validation with Ensure.Guid Source: https://context7.com/danielwertheim/ensure.that/llms.txt Use Ensure.Guid to validate that GUID arguments are not empty (Guid.Empty). Essential for ensuring unique identifiers are provided. ```csharp using EnsureThat; using System; public class EntityRepository { public void GetById(Guid entityId) { // Ensure GUID is not Guid.Empty Ensure.Guid.IsNotEmpty(entityId, nameof(entityId)); } public void LinkEntities(Guid parentId, Guid childId) { Ensure.Guid.IsNotEmpty(parentId, nameof(parentId)); Ensure.Guid.IsNotEmpty(childId, nameof(childId)); } } ``` -------------------------------- ### Create Custom String Validation Extension (Contextual API) Source: https://context7.com/danielwertheim/ensure.that/llms.txt Extend the library with custom validation methods for domain-specific rules using the contextual API. This example adds an `IsValidEmail` check. ```csharp using EnsureThat; // Extension for contextual API public static class CustomStringArgExtensions { public static string IsValidEmail(this StringArg _, string value, string paramName = null) { if (!value.Contains("@") || !value.Contains(".")) throw Ensure.ExceptionFactory.ArgumentException( "Value must be a valid email address", paramName); return value; } } ``` -------------------------------- ### Create Custom String Validation Extension (Static API) Source: https://context7.com/danielwertheim/ensure.that/llms.txt Extend the library with custom validation methods for domain-specific rules using the static API. This example adds an `IsValidEmail` check. ```csharp using EnsureThat; // Extension for static API public static partial class EnsureArg { public static string IsValidEmail(string value, string paramName = null) { if (!value.Contains("@") || !value.Contains(".")) throw Ensure.ExceptionFactory.ArgumentException( "Value must be a valid email address", paramName); return value; } } ``` -------------------------------- ### Create Custom String Validation Extension (Fluent API) Source: https://context7.com/danielwertheim/ensure.that/llms.txt Extend the library with custom validation methods for domain-specific rules using the fluent API. This example adds an `IsValidEmail` check. ```csharp using EnsureThat; // Extension for fluent API public static class CustomStringExtensions { public static StringParam IsValidEmail(this StringParam param) { if (!param.Value.Contains("@") || !param.Value.Contains(".")) throw Ensure.ExceptionFactory.ArgumentException( "Value must be a valid email address", param.Name); return param; } } ``` -------------------------------- ### Contextual String Validation with Ensure.String Source: https://context7.com/danielwertheim/ensure.that/llms.txt Utilize Ensure.String for efficient string argument validation without wrapper objects. Supports null/empty checks, GUID format validation, length constraints, and pattern matching. ```csharp using EnsureThat; public class DocumentService { public void SaveDocument(string title, string content, string authorId) { // Simple null/empty checks Ensure.String.IsNotNullOrWhiteSpace(title, nameof(title)); Ensure.String.IsNotNullOrEmpty(content, nameof(content)); // Validate string is a valid GUID format Guid parsedAuthorId = Ensure.String.IsGuid(authorId, nameof(authorId)); // Length constraints Ensure.String.HasLengthBetween(title, 1, 255, nameof(title)); // Pattern matching Ensure.String.StartsWith(authorId, "usr-", nameof(authorId)); } } ``` -------------------------------- ### Extending Ensure.Context with Custom String Validation Source: https://github.com/danielwertheim/ensure.that/blob/master/README.md Custom validation logic for strings can be added to Ensure.Context by extending the StringArg class. This example shows how to add an 'IsNotFishy' validation. ```csharp public static class StringArgExtensions { public static string IsNotFishy(this StringArg _, string value, string paramName = null) => value != "fishy" ? value : throw Ensure.ExceptionFactory.ArgumentException("Something is fishy!", paramName); } Ensure.String.IsNotFishy(myString, nameof(myString)); ``` -------------------------------- ### Extending EnsureArg with Custom Static Validation Source: https://github.com/danielwertheim/ensure.that/blob/master/README.md Custom validation methods can be added to the EnsureArg class. This example demonstrates adding an 'IsNotFishy' validation method. ```csharp public static partial class EnsureArg { public static string IsNotFishy(string value, string paramName = null) => value != "fishy" ? value : throw Ensure.ExceptionFactory.ArgumentException("Something is fishy!", paramName); } EnsureArg.IsNotFishy(myString, nameof(myString)); ``` -------------------------------- ### Static Method Validation with EnsureArg Source: https://context7.com/danielwertheim/ensure.that/llms.txt Employ EnsureArg for the most performant validation via static method calls, avoiding object allocation. Examples include null/whitespace checks, value comparisons, length constraints, and character validation. ```csharp using EnsureThat; public class PaymentProcessor { public void ProcessPayment(string cardNumber, decimal amount, string currency) { // Static method validation - no object allocation EnsureArg.IsNotNullOrWhiteSpace(cardNumber, nameof(cardNumber)); EnsureArg.IsGt(amount, 0m, nameof(amount)); EnsureArg.HasLength(currency, 3, nameof(currency)); EnsureArg.IsAllLettersOrDigits(currency, nameof(currency)); } } ``` -------------------------------- ### Validate Lambda Expression Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Use lambda expressions with `Ensure.That` to validate properties or expressions, providing better refactoring support. This example checks if a person's name is not null or empty. ```csharp Ensure.That(() => person.Name).IsNotNullOrEmpty(); ``` -------------------------------- ### Running Unit Tests Source: https://github.com/danielwertheim/ensure.that/blob/master/README.md Unit tests are written using xUnit. You can run them by navigating to the source directory and executing 'dotnet test'. ```bash dotnet test src/ ``` -------------------------------- ### Develop as .NET Standard 1.1 project Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md The project is now developed exclusively as a .NET Standard 1.1 project. ```csharp (Changed): Now developed as only a .NET Standard 1.1 project. ``` -------------------------------- ### Signed assembly with SNK Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md The assembly is now signed with a Strong Name Key (SNK) for identification purposes. ```csharp (Changed): The assembly is now signed with a SNK, not for security purposes but for identification purposes and the key is in the repo. ``` -------------------------------- ### Usage of Custom Email Validation Source: https://context7.com/danielwertheim/ensure.that/llms.txt Demonstrates how to use custom email validation extensions with fluent, contextual, and static APIs. ```csharp // Usage public class EmailService { public void SendEmail(string to) { // Fluent Ensure.That(to, nameof(to)).IsNotNullOrWhiteSpace().IsValidEmail(); // Contextual Ensure.String.IsValidEmail(to, nameof(to)); // Static EnsureArg.IsValidEmail(to, nameof(to)); } } ``` -------------------------------- ### Add Any() for dictionaries Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Introduces the Any() method for dictionaries, allowing checks for emptiness. ```csharp (New): `Any` for dictionaries. ``` -------------------------------- ### Remove Ensure.On/Off support Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Support for Ensure.On/Off has been removed to improve performance. ```csharp (Dropped): `Ensure.On/Off` support has been removed in order to get better performance. ``` -------------------------------- ### Add StartsWith validation Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Introduces StartsWith validation for strings, available via Ensure.That, Ensure.String, and EnsureArg. ```csharp (New): `Ensure.That(string).StartsWith(...)`, `Ensure.String.StartsWith(...)`, `EnsureArg.StartsWith` ``` -------------------------------- ### Add Lambda Expression Support (Alternative 2) Source: https://github.com/danielwertheim/ensure.that/wiki/Home An alternative extension method for lambda expression support, which includes handling a default parameter name. This implementation is based on a pull request by Filip Ekberg. ```csharp public static Param That(Expression> expression, string name = Param.DefaultName) { if (name == Param.DefaultName) { var memberExpressionBody = (MemberExpression)expression.Body; name = memberExpressionBody.Member.Name; } return new Param(name, expression.Compile().Invoke(null)); } ``` -------------------------------- ### Implement Custom Exception Factory Source: https://context7.com/danielwertheim/ensure.that/llms.txt Replace the default exception factory to customize exception types and messages. Configure this globally at application startup. ```csharp using EnsureThat; using System; public class CustomExceptionFactory : IExceptionFactory { public Exception ArgumentException(string defaultMessage, string paramName) => new CustomValidationException($"Validation failed for '{paramName}': {defaultMessage}"); public Exception ArgumentNullException(string defaultMessage, string paramName) => new CustomValidationException($"Required parameter '{paramName}' was null"); public Exception ArgumentOutOfRangeException(string defaultMessage, string paramName, TValue value) => new CustomValidationException($"Parameter '{paramName}' with value '{value}' is out of range: {defaultMessage}"); } public class CustomValidationException : Exception { public CustomValidationException(string message) : base(message) { } } // Configure globally at application startup public class Startup { public void Configure() { Ensure.ExceptionFactory = new CustomExceptionFactory(); } } ``` -------------------------------- ### Add Lambda Expression Support (Alternative 1) Source: https://github.com/danielwertheim/ensure.that/wiki/Home Use this extension method to re-introduce lambda expression support for parameter evaluation. It requires the `System.Linq.Expressions` namespace. ```csharp public static Param That(Expression> expression) { var memberExpression = expression.GetRightMostMember(); return new Param( memberExpression.ToPath(), expression.Compile().Invoke()); } ``` -------------------------------- ### Object Validation with Ensure.Any Source: https://context7.com/danielwertheim/ensure.that/llms.txt Use Ensure.Any to validate that objects are not null and value types are not their default values. Includes a fluent API alternative for null checks. ```csharp using EnsureThat; public class OrderService { public void PlaceOrder(Order order, Customer customer, DateTime orderDate) { // Null check for reference types Ensure.Any.IsNotNull(order, nameof(order)); Ensure.Any.IsNotNull(customer, nameof(customer)); // Ensure value type is not default Ensure.Any.IsNotDefault(orderDate, nameof(orderDate)); // Fluent API alternative Ensure.That(order, nameof(order)).IsNotNull(); } } ``` -------------------------------- ### Rename Any() to HasAny() Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md The methods EnsureArg.Any() and Ensure.That(...).Any() have been renamed to EnsureArg.HasAny() and Ensure.That(...).HasAny() to align with Ensure.Collection.HasAny. ```csharp (Changed): `EnsureArg.Any()` and `Ensure.That(...).Any()` is now called `EnsureArg.HasAny` and `Ensure.That(...).HasAny()` to match `Ensure.Collection.HasAny` ``` -------------------------------- ### Mark fluent Ensure.That syntax as Obsolete Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md The fluent Ensure.That syntax is now marked as Obsolete, encouraging the use of contextual validations like Ensure.String.IsNotNull or EnsureArg.IsNotNull. ```csharp (Obsolete warning): The "fluent" `Ensure.That` syntax has been marked as `Obsolete` in favour for either the contextual validations: `Ensure.String.IsNotNull(..., ...);` or `EnsureArg.IsNotNull(..., ...);` The obsolete versions will be removed in next major version. ``` -------------------------------- ### Expression Extension Methods for Path and Member Retrieval Source: https://github.com/danielwertheim/ensure.that/wiki/Home Utility methods to assist with processing expressions, including extracting the right-most member and converting it to a string path. These are used by the alternative lambda support methods. ```csharp internal static class ExpressionExtensions { internal static string ToPath(this MemberExpression e) { var path = ""; var parent = e.Expression as MemberExpression; if (parent != null) path = parent.ToPath() + "."; return path + e.Member.Name; } internal static MemberExpression GetRightMostMember(this Expression e) { if (e is LambdaExpression) return GetRightMostMember(((LambdaExpression)e).Body); if (e is MemberExpression) return (MemberExpression)e; if (e is MethodCallExpression) { var callExpression = (MethodCallExpression)e; if (callExpression.Object is MethodCallExpression || callExpression.Object is MemberExpression) return GetRightMostMember(callExpression.Object); var member = callExpression.Arguments.Count > 0 ? callExpression.Arguments[0] : callExpression.Object; return GetRightMostMember(member); } if (e is UnaryExpression) { var unaryExpression = (UnaryExpression)e; return GetRightMostMember(unaryExpression.Operand); } return null; } } ``` -------------------------------- ### Boolean Validation with Ensure.Bool Source: https://context7.com/danielwertheim/ensure.that/llms.txt Utilize Ensure.Bool to validate that boolean arguments are true or false as expected. Useful for checking preconditions like administrative privileges or feature flags. ```csharp using EnsureThat; public class FeatureToggle { public void EnableFeature(string featureName, bool isAdmin, bool hasLicense) { Ensure.String.IsNotNullOrWhiteSpace(featureName, nameof(featureName)); // Require admin privileges Ensure.Bool.IsTrue(isAdmin, nameof(isAdmin)); // Ensure license is present Ensure.Bool.IsTrue(hasLicense, nameof(hasLicense)); } public void DisableMaintenanceMode(bool isMaintenanceActive) { // Ensure maintenance is not active before disabling Ensure.Bool.IsFalse(isMaintenanceActive, nameof(isMaintenanceActive)); } } ``` -------------------------------- ### Numeric and Comparable Validation with Ensure.Comparable Source: https://context7.com/danielwertheim/ensure.that/llms.txt Use Ensure.Comparable for validating numeric values against ranges, equality, and comparison operations. Requires values to implement IComparable. ```csharp using EnsureThat; using System; public class TemperatureMonitor { public void SetThreshold(int minTemp, int maxTemp, decimal precision) { // Greater than / less than checks Ensure.Comparable.IsGt(maxTemp, minTemp, nameof(maxTemp)); Ensure.Comparable.IsGte(precision, 0.01m, nameof(precision)); Ensure.Comparable.IsLte(precision, 1.0m, nameof(precision)); // Range validation (inclusive) Ensure.Comparable.IsInRange(minTemp, -50, 150, nameof(minTemp)); Ensure.Comparable.IsInRange(maxTemp, -50, 150, nameof(maxTemp)); // Equality checks Ensure.Comparable.IsNot(minTemp, maxTemp, nameof(minTemp)); } public void LogReading(DateTime timestamp, double temperature) { // DateTime comparison Ensure.Comparable.IsLte(timestamp, DateTime.UtcNow, nameof(timestamp)); Ensure.Comparable.IsGt(timestamp, DateTime.UtcNow.AddDays(-1), nameof(timestamp)); } } ``` -------------------------------- ### Fix EnsureArg.IsTrue/IsFalse optsFn passing Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Corrects an issue where EnsureArg.IsTrue and EnsureArg.IsFalse did not correctly pass down the optsFn parameter. ```csharp (Fix): `EnsureArg.IsTrue` and `EnsureArg.IsFalse` did not pass `optsFn` down. ``` -------------------------------- ### Add HasItems for IReadOnlyCollection and IReadOnlyList Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Introduces the HasItems method for IReadOnlyCollection and IReadOnlyList interfaces. ```csharp (New): `HasItems` for `IReadOnlyCollection` and `IReadOnlyList`. ``` -------------------------------- ### Basic Argument Validation with Ensure.That Source: https://github.com/danielwertheim/ensure.that/blob/master/README.md Use Ensure.That with extension methods for basic argument validation like checking for null or whitespace. The optional second parameter can specify the argument name. ```csharp Ensure.That(myString).IsNotNullOrWhiteSpace(); ``` ```csharp Ensure.That(myString, nameof(myString)).IsNotNullOrWhiteSpace(); ``` -------------------------------- ### Collection Validation with Ensure.Collection Source: https://context7.com/danielwertheim/ensure.that/llms.txt Validate collections (lists, dictionaries, arrays) for item presence, size, key existence, and predicate matching. Demonstrates checking for items, exact size, specific keys, and elements satisfying a condition. ```csharp using EnsureThat; using System.Collections.Generic; public class BatchProcessor { public void ProcessBatch(List items, Dictionary metadata) { // Ensure collection has items Ensure.Collection.HasItems(items, nameof(items)); Ensure.Collection.HasItems(metadata, nameof(metadata)); // Validate exact size Ensure.Collection.SizeIs(items, 10, nameof(items)); // Check dictionary contains required key Ensure.Collection.ContainsKey(metadata, "version", nameof(metadata)); // Predicate-based validation Ensure.Collection.HasAny(items, x => x.StartsWith("priority-"), nameof(items)); } public void ProcessArray(int[] numbers) { Ensure.Collection.HasItems(numbers, nameof(numbers)); Ensure.Collection.SizeIs(numbers, 5, nameof(numbers)); } } ``` -------------------------------- ### Update Ensure.That fluent syntax Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md The fluent Ensure.That syntax has been updated. Param is now a struct, and the overload accepting a Func has been removed. Message and exception customization now uses a unified construct. ```csharp (Changed): The "fluent" `Ensure.That` syntax that previously was marked as `Obsolete` has been kept with some slight changes. E.g. `Param` is now a struct. The overload of `Ensure.That(...)` accepting a `Func` has been removed. Options to customize messages and expceptions now uses the same construct as the other APIs. ``` -------------------------------- ### Accept IComparer for value comparisons Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Validation methods that compare values now accept an optional IComparer for custom comparison logic. ```csharp (New): Methods that are comparing values now accepts an optional `IComparer` ``` -------------------------------- ### Fluent Validation with Ensure.That() Source: https://context7.com/danielwertheim/ensure.that/llms.txt Use the fluent API for chainable validations on method arguments. Basic validation with optional parameter name and numeric range checks are demonstrated. ```csharp using EnsureThat; public class UserService { public void CreateUser(string username, string email, int age) { // Basic validation with optional parameter name Ensure.That(username, nameof(username)).IsNotNullOrWhiteSpace(); // Chainable validations on the same value Ensure .That(email, nameof(email)) .IsNotNullOrWhiteSpace() .Matches(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"); // Numeric range validation Ensure.That(age, nameof(age)).IsInRange(18, 120); } } ``` -------------------------------- ### Use ContractAnnotationAttribute Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Integrates ContractAnnotationAttribute for improved static analysis and code understanding. ```csharp (New): Now makes use of `ContractAnnotationAttribute` ``` -------------------------------- ### Chained Argument Validation with Ensure.That Source: https://github.com/danielwertheim/ensure.that/blob/master/README.md Validation rules can be chained together using Ensure.That extension methods for sequential checks on an argument. ```csharp Ensure .That(myString) .IsNotNullOrWhiteSpace() .IsGuid(); ``` -------------------------------- ### Correct assembly name Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Corrected the assembly name from EnsureThat.dll to Ensure.That.dll to match previous versions. ```csharp (Fix): Corrected assembly name to be same as previous: `Ensure.That.dll` instead of `EnsureThat.dll` ``` -------------------------------- ### Check for Not Null or Empty String Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Use this to quickly check if a string argument is not null or empty. This is a simplified API with less overhead. ```csharp EnsureArg.IsNotNullOrEmpty(myString) ``` -------------------------------- ### Contextual String Validation with Ensure.Context Source: https://github.com/danielwertheim/ensure.that/blob/master/README.md Introduced in v7.0.0, Ensure.Context provides contextual validation methods, such as IsNotNullOrWhiteSpace for strings. The optional second parameter can specify the argument name. ```csharp Ensure.String.IsNotNullOrWhiteSpace(myString); ``` ```csharp Ensure.String.IsNotNullOrWhiteSpace(myString, nameof(myArg)); ``` -------------------------------- ### Check String Equality Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Validate if a string is exactly equal to a specified string. Case-sensitive comparison. ```csharp Ensure.That(string).IsEqualTo("foo") ``` -------------------------------- ### Check String Inequality Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Validate if a string is not exactly equal to a specified string. Case-sensitive comparison. ```csharp Ensure.That(string).IsNotEqualTo("foo") ``` -------------------------------- ### Add attributes for ReSharper integration Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Includes additional attributes to enhance Ensure.That's compatibility and understanding with ReSharper. ```csharp (New): Added more attributes to the API to get ReSharper to "understand" Ensure.That better. ``` -------------------------------- ### Custom Exception with WithException Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Replace the default exception with a custom one using the `WithException` overload. This provides more control over error handling. ```csharp Ensure .That(myString, nameof(myString)) .WithException(param => new Exception()) .IsNotNullOrEmpty(); ``` -------------------------------- ### Add contextual validation Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Introduces contextual validation, allowing for more specific checks like Ensure.String.IsNotNull(myString, nameof(myString)). ```csharp (New): Contextual validation, e.g. `Ensure.String.IsNotNull(myString, nameof(myString));` ``` -------------------------------- ### Add Ensure.Enumerable for IEnumerable Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Introduces Ensure.Enumerable, which provides similar functionality to Ensure.Collection but operates on IEnumerable. Note that enumeration will occur. ```csharp (New): Added `Ensure.Enumerable` which provides the members found in `Ensure.Collection` but it operates on `IEnumerable` instead. **Please note that enumeration will occur**. ``` -------------------------------- ### Extending Ensure.That with Custom Validation Source: https://github.com/danielwertheim/ensure.that/blob/master/README.md You can easily extend Ensure.That by creating custom extension methods for the StringParam type to implement specific validation logic. ```csharp public static class StringArgExtensions { public static StringParam IsNotFishy(this StringParam param) => param.Value != "fishy" ? param : throw Ensure.ExceptionFactory.ArgumentException("Something is fishy!", param.Name); } Ensure.That(myString, nameof(myString)).IsNotFishy(); ``` -------------------------------- ### Comparable validations use IComparable Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Comparable validations (e.g., Lt, Gt) are no longer restricted to structs and now operate against IComparable. ```csharp (Changed): Comparable validations e.g. `Lt`, `Gt` etc.; are not tied to `struct` anymore. Only against `IComparable`. ``` -------------------------------- ### Add IsEmptyOrWhiteSpace validation Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Introduces a new validation method IsEmptyOrWhiteSpace to check if a string is null, empty, or contains only whitespace. ```csharp (New): Adds `IsEmptyOrWhiteSpace` ``` -------------------------------- ### Determine Custom Exceptions Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Specify custom exceptions to be thrown instead of the default `ArgumentException`. This allows for more specific error handling tailored to your application's needs. ```csharp Ensure.That(value, ParamName) .IsNotNull(throws => throws.InvalidOperationException)); ``` ```csharp Ensure.That(value, ParamName) .IsNotNull(throws => throws.Custom(p => new Exception("Ooops")))); ``` -------------------------------- ### Simple Static Argument Validation with EnsureArg Source: https://github.com/danielwertheim/ensure.that/blob/master/README.md Introduced in v5.0.0, EnsureArg offers simple static methods for argument validation, like IsNotNullOrWhiteSpace. The optional second parameter can specify the argument name. ```csharp EnsureArg.IsNotNullOrWhiteSpace(myString); ``` ```csharp EnsureArg.IsNotNullOrWhiteSpace(myString, nameof(myArg)); ``` -------------------------------- ### Fix IsNotEmptyOrWhiteSpace for partial whitespace strings Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Addresses an issue where passing a string with only partial whitespace to IsNotEmptyOrWhiteSpace caused incorrect validation. ```csharp (Fix): Fixes passing partial white-space string to `IsNotEmptyOrWhiteSpace`. ``` -------------------------------- ### Chaining Validations with And() Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Chain multiple validations for improved readability. The `And()` method explicitly separates consecutive validation checks. ```csharp Ensure.That(string).IsNotNull().And().SizeIs(2) ``` -------------------------------- ### Type Validation with Ensure.Type Source: https://context7.com/danielwertheim/ensure.that/llms.txt Perform runtime type validation using Ensure.Type, checking for class types, assignability to interfaces, specific type instances, and primitive types. Also includes checks for forbidden types. ```csharp using EnsureThat; using System; public interface IPlugin { } public class MyPlugin : IPlugin { } public class PluginLoader { public void LoadPlugin(object plugin, Type pluginType) { // Validate type is a class Ensure.Type.IsClass(pluginType, nameof(pluginType)); // Validate type is assignable to interface Ensure.Type.IsAssignableToType(pluginType, typeof(IPlugin), nameof(pluginType)); // Validate object is of specific type Ensure.Type.IsOfType(plugin, typeof(MyPlugin), nameof(plugin)); } public void ValidateConfig(object config) { // Validate specific primitive types Ensure.Type.IsString(config, nameof(config)); // Or: Ensure.Type.IsInt(config, nameof(config)); // Or: Ensure.Type.IsDateTime(config, nameof(config)); } public void RegisterService(T service) where T : class { // Validate type is not of a forbidden type Ensure.Type.IsNotOfType(service, typeof(object), nameof(service)); Ensure.Type.IsNotAssignableToType(service, typeof(IDisposable), nameof(service)); } } ``` -------------------------------- ### Check Collection for Any Matching Element Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Validate that any element within an array, list, or collection satisfies a given condition using a lambda expression. ```csharp Ensure.That(array|list|collection).Any(i => i == x); ``` -------------------------------- ### Check Dictionary Key Existence Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Validate that a dictionary contains a specific key. This is a common check for ensuring data integrity. ```csharp Ensure.That(dictionary).ContainsKey("foo"); ``` -------------------------------- ### Check Collection Size Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Validate that an array, collection, or string has a specific size. This is useful for ensuring the correct number of elements or characters. ```csharp Ensure.That(array|collection|string).SizeIs(2) ``` -------------------------------- ### Chaining Validations with Extra Message Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Chain multiple validations and provide an extra descriptive message using a lambda expression. The `Param` argument allows access to the parameter's metadata. ```csharp Ensure .That(myString, nameof(myString)) .WithExtraMessageOf(p => "Some more details") .IsNotNullOrEmpty(); ``` -------------------------------- ### Ensure parameter IsNotNull where applicable Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Validation methods now ensure the parameter is not null, throwing an ArgumentNullException if it is. This eliminates the need for separate IsNotNull checks in most cases. ```csharp (Changed): Where applicable, validation methods now ensures that the param `IsNotNull`. If it is, an `ArgumentNullException` is thrown. So there is no need to do both. How-ever, some calls are not applicable to this, like `EnsureArg.IsNotEmpty(myString)`. ``` -------------------------------- ### Return value assignment with EnsureArg Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md EnsureArg methods now return the evaluated value, enabling assignment to fields or variables, e.g., `_field = EnsureArg.IsNotNull(myArg, nameof(myArg))`. ```csharp (New): `EnsureArg.Abcdefg(...)` methods now returns the value so that it can be assigned to e.g. fields: `_field = EnsureArg.IsNotNull(myArg, nameof(myArg))`. ``` -------------------------------- ### Check Numeric Equality Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Validate if a numeric value is equal to a specific number. Supports various numeric types due to `IComparable`. ```csharp Ensure.That(int|decimal|...|).Is(1) ``` -------------------------------- ### Enum Validation with Ensure.Enum Source: https://context7.com/danielwertheim/ensure.that/llms.txt Validate enum values using Ensure.Enum to ensure they are defined within their enumeration type. Supports standard enums and flags-aware validation for [Flags] enums. ```csharp using EnsureThat; using System; public enum OrderStatus { Pending = 1, Processing = 2, Shipped = 3, Delivered = 4 } [Flags] public enum Permissions { None = 0, Read = 1, Write = 2, Delete = 4, Admin = 7 } public class OrderManager { public void UpdateStatus(Guid orderId, OrderStatus newStatus) { Ensure.Guid.IsNotEmpty(orderId, nameof(orderId)); // Validate enum is a defined value Ensure.Enum.IsDefined(newStatus, nameof(newStatus)); } public void SetPermissions(Guid userId, Permissions permissions) { Ensure.Guid.IsNotEmpty(userId, nameof(userId)); // Use flags-aware validation for [Flags] enums Ensure.Enum.IsDefinedWithFlagsSupport(permissions, nameof(permissions)); } } ``` -------------------------------- ### Check Numeric Inequality Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Validate if a numeric value is not equal to a specific number. Supports various numeric types due to `IComparable`. ```csharp Ensure.That(int|decimal|...|).IsNot(1) ``` -------------------------------- ### ArgumentOutOfRangeException for comparing validations Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Comparing validation checks (e.g., Lt, Gt, Between) now throw an ArgumentOutOfRangeException instead of an ArgumentException. ```csharp (Changed): When using comparing validation checks, e.g.`Lt`, `Gt`, `Between` etc.; An `ArgumentOutOfRangeException` is thrown instead of an `ArgumentException`. ``` -------------------------------- ### Prevent chaining on validation methods Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Chaining any method after an actual validation method (e.g., IsNotNull) in the Ensure.That(arg) construct is no longer supported, as the call tree would terminate early. ```csharp (Changed): When using the `Ensure.That(arg)` construct, it allows you to use e.g `WithException(_ => new Exception("Foo"))`. This could be appended after an validation method e.g. `IsNotNull`. How-ever, doing so would not kick the custom exception factory as the call tree would get terminated before, in the `IsNotNull` method. From now on, you can not chain anything on the actual validation method. ``` -------------------------------- ### Decorate parameters with NotNullAttribute and ValidatedNotNull Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md When using EnsureArg, the evaluated parameter is now decorated with JetBrains NotNullAttribute and a custom ValidatedNotNull attribute to mitigate CA1062 warnings. ```csharp (New): When using `EnsureArg`, the param being evaluated is now decorated with JetBrains `NotNullAttribute` and custom `ValidatedNotNull` (to get rid of `CA1062`). ``` -------------------------------- ### Add [NoEnumeration] attribute to IsNotNull Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md The [NoEnumeration] attribute has been added to IsNotNull to help suppress potential warnings. ```csharp (New): Added JetBrain's attribute `[NoEnumeration]` on `IsNotNull` to get rid of warning. Thanks @megafinz ``` -------------------------------- ### Add custom exception message/type to EnsureArg Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Provides overloads for EnsureArg and contextual types like Ensure.StringArg to specify custom exception messages or exception types. ```csharp (New): Added overload to `EnsureArg` and contextual e.g. `Ensure.StringArg` that allows you to define either a custom exception message or custom exception. ``` -------------------------------- ### Fix SizeIs comparison with long Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Corrects the SizeIs method to use Array.LongLength when comparing against a long value. ```csharp (Fix): `SizeIs` did not compare against `Array.LongLength` when passed a `long`. ``` -------------------------------- ### Turn Off Validation Source: https://github.com/danielwertheim/ensure.that/blob/master/ReleaseNotes.md Use `Ensure.Off()` to temporarily disable all validation checks within the library. This can be useful for performance-critical sections or specific testing scenarios. ```csharp Ensure.Off(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.