Skip to content

Fluent guard clauses for .NET — throw exceptions in one expressive line with auto-captured argument names

Notifications You must be signed in to change notification settings

phmatray/CCross.ThrowIf

Repository files navigation

CCross.ThrowIf — Fluent guard clauses for .NET

NuGet License Stars

CCross.ThrowIf is a lightweight C# library that provides expressive, fluent guard clauses for argument validation and exception throwing. Stop writing boilerplate if (...) throw new ... blocks — express your preconditions cleanly in one line.

✨ Features

  • Fluent guard clausesThrowIf.Argument.IsNull, IsNullOrEmpty, IsGreaterThan, and more
  • Strongly-typed expressions — uses Expression<Func<T>> to automatically capture the argument name (no more nameof(...))
  • Multiple type support — works with string, int, long, float, double, decimal, bool, DateTime, TimeSpan
  • Generic overloadsThrowIf<TException> lets you specify the exception type to throw
  • Clean API — organized into logical categories: Argument, Collection, Value, ArrayIndex
  • Zero dependencies — pure .NET Portable Class Library

📦 Installation

dotnet add package CCrossThrowIf

Or via the NuGet Package Manager:

Install-Package CCrossThrowIf

Note: Targets .NET Portable (Profile 7 / .NET 4.5+). Compatible with .NET Standard projects.

🚀 Quick Start

using CCrossThrowIf;

public class OrderService
{
    public void PlaceOrder(string customerId, int quantity, decimal amount)
    {
        // Throws ArgumentNullException with auto-captured argument name
        ThrowIf.Argument.IsNullOrWhiteSpace(() => customerId);

        // Throws ArgumentOutOfRangeException if quantity <= 0
        ThrowIf.Argument.IsNegativeOrZero(() => quantity);

        // Throws ArgumentOutOfRangeException if amount > 10000
        ThrowIf.Argument.IsGreaterThan(() => amount, limit: 10000m, "Order amount exceeds maximum.");

        // Process the order...
    }
}

Generic exception type

// Throw any exception type with the same fluent API
ThrowIf<InvalidOperationException>.IsNull(() => myService);
ThrowIf<ArgumentOutOfRangeException>.IsNullOrEmpty(() => configValue, "Config must be set.");

DateTime validation

ThrowIf.Argument.IsInThePast(() => scheduledDate);
ThrowIf.Argument.IsInTheFuture(() => auditTimestamp);

Bool validation

ThrowIf.Argument.IsTrue(() => isLocked, "Resource is locked and cannot be modified.");
ThrowIf.Argument.IsFalse(() => isInitialized);

📖 Documentation

Full API reference and examples available at the project website.

🤝 Contributing

Pull requests welcome. See CONTRIBUTING.md if available, or open an issue to discuss your changes.

📄 License

MIT — see LICENSE

About

Fluent guard clauses for .NET — throw exceptions in one expressive line with auto-captured argument names

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published