A shopper entering six items when only five are available needs a useful rejection. A negative stock count passed by application code needs a different response. Returning the same “invalid input” result for both can hide a defect and send the shopper back to a form they cannot fix.
This tutorial defines that boundary with an explicit result, an argument exception, and a test that detects a wrapper which confuses them. The complete program targets .NET 10, uses only the base class library, and was compiled and run in an isolated offline SDK container on November 9, 2026.
Choose the contract from the caller’s next action
Microsoft recommends checking routine error conditions and handling exceptions where recovery is possible. It recommends predefined argument exceptions for invalid method arguments. Those are design guidelines, rather than a rule that every failure must use one channel. See best practices for exceptions.
| Condition | Signal | Caller action |
|---|---|---|
| Missing or malformed quantity text | Explicit error result | Ask for a whole number. |
| Zero, negative, or unavailable quantity | Explicit error result | Explain the quantity rule. |
| Negative stock argument | ArgumentOutOfRangeException | Investigate invalid application state or configuration. |
| Accepted quantity | No error plus the parsed quantity | Continue to the next application step. |
Here, text is untrusted form input, while stock must already be a nonnegative internal count. That ownership decision explains why the two parameters use different failure channels. If stock itself came directly from a form, validate it at that boundary before invoking this method.
The result is a named tuple containing an error enum and a quantity. QuantityError.None means success. On rejection the quantity is zero and must not be consumed. A Boolean would suffice if every rejection had the same caller action; the enum distinguishes the responses this example needs.
Run the complete contract test
Create a console project with a .NET 10 SDK, replace its entire Program.cs with the program below, and run it. No test-framework package is required.
dotnet new console --framework net10.0 --name QuantityContract
cd QuantityContract
dotnet run
The parser uses a fixed integer style and invariant culture. The string/style/provider TryParse overload returns false for malformed or out-of-range text. Its Boolean result controls whether the parsed number is usable. Our wrapper then applies the quantity rules; parsing alone cannot decide whether an order quantity is acceptable.
using System;
using System.Globalization;
static class Program
{
enum QuantityError { None, Missing, InvalidInteger, NotPositive, ExceedsStock }
static (QuantityError Error, int Quantity) CheckQuantity(string? text, int stock)
{
ArgumentOutOfRangeException.ThrowIfNegative(stock);
if (string.IsNullOrWhiteSpace(text))
return (QuantityError.Missing, 0);
if (!int.TryParse(text, NumberStyles.Integer,
CultureInfo.InvariantCulture, out int quantity))
return (QuantityError.InvalidInteger, 0);
if (quantity <= 0)
return (QuantityError.NotPositive, 0);
if (quantity > stock)
return (QuantityError.ExceedsStock, 0);
return (QuantityError.None, quantity);
}
// Deliberate defect: hides a programming/configuration error as user input.
static (QuantityError Error, int Quantity) BrokenCheck(string? text, int stock)
{
try { return CheckQuantity(text, stock); }
catch (ArgumentException) { return (QuantityError.InvalidInteger, 0); }
}
static void Require(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
static void RequiresInvalidStock(Action action)
{
try { action(); }
catch (ArgumentOutOfRangeException error)
{
Require(error.ParamName == "stock", "Wrong invalid argument.");
return;
}
throw new InvalidOperationException("Invalid stock must throw.");
}
static void Main()
{
bool defectDetected = false;
try { RequiresInvalidStock(() => BrokenCheck("1", -1)); }
catch (InvalidOperationException) { defectDetected = true; }
Require(defectDetected, "Harness missed the swallowed exception.");
Console.WriteLine("Broken wrapper: swallowed exception detected");
(string? Text, int Stock, QuantityError Error, int Quantity)[] cases =
{
(null, 5, QuantityError.Missing, 0),
(" ", 5, QuantityError.Missing, 0),
("two", 5, QuantityError.InvalidInteger, 0),
("2147483648", 5, QuantityError.InvalidInteger, 0),
("0", 5, QuantityError.NotPositive, 0),
("-1", 5, QuantityError.NotPositive, 0),
("6", 5, QuantityError.ExceedsStock, 0),
("1", 0, QuantityError.ExceedsStock, 0),
("1", 5, QuantityError.None, 1),
("5", 5, QuantityError.None, 5),
(" +2 ", 5, QuantityError.None, 2)
};
foreach (var item in cases)
{
var actual = CheckQuantity(item.Text, item.Stock);
Require(actual.Error == item.Error && actual.Quantity == item.Quantity,
"Wrong quantity result for: " + (item.Text ?? "<null>"));
}
Console.WriteLine("Quantity contract: 11 cases passed");
RequiresInvalidStock(() => CheckQuantity("1", -1));
RequiresInvalidStock(() => CheckQuantity(null, -1));
Console.WriteLine("Invalid stock: 2 exception checks passed");
var accepted = CheckQuantity("2", 5);
if (accepted.Error == QuantityError.None)
Console.WriteLine($"Caller accepted: {accepted.Quantity}");
else
throw new InvalidOperationException("Expected accepted quantity.");
var rejected = CheckQuantity("6", 5);
if (rejected.Error == QuantityError.ExceedsStock)
Console.WriteLine("Caller rejected: choose a smaller quantity");
else
throw new InvalidOperationException("Expected stock rejection.");
}
}
The asserted application output is exactly:
Broken wrapper: swallowed exception detected
Quantity contract: 11 cases passed
Invalid stock: 2 exception checks passed
Caller accepted: 2
Caller rejected: choose a smaller quantity
Read both the failing and passing cases
BrokenCheck deliberately catches an argument exception and changes it into InvalidInteger. The negative stock count therefore looks like bad user text. RequiresInvalidStock rejects that behavior because it requires an ArgumentOutOfRangeException naming stock. The outer test expects this assertion failure and checks that it occurred. The first output line reports a detected defect; the overall program succeeds only when that detection works.
The corrected CheckQuantity has no catch that translates its precondition failure. Its 11 table cases assert both the enum and the quantity: null and whitespace are missing, letters and integer overflow are invalid integers, zero and minus one are not positive, and quantities above available stock are rejected. One and five exercise the accepted lower and stock boundaries. The signed, padded input exercises the chosen parsing style.
The two exception checks include null text with negative stock. They establish precedence: invalid internal stock throws before any input error result is returned. Changing the order of those checks changes this contract, so keep a test for that combination.
The final two calls illustrate caller policy. The successful branch consumes the quantity only after checking for no error. The stock rejection selects a useful message without catching an exception. The enum is a programmatic outcome, so user-facing wording can change independently.
Keep the boundary useful as the application grows
Keep exception handling at a layer that can act on the failure. A broad catch that returns an ordinary validation result can conceal problems the caller should investigate. Microsoft’s recovery guidance recommends allowing exceptions to reach an appropriate caller when the current method cannot recover.
This tuple is a small local contract, not a general result library. Its type permits contradictory combinations if other code constructs it freely. For a public API, decide how to constrain construction and document which errors callers can handle before expanding the result shape. Adding an enum value also requires reviewing caller policies and tests.
The fixture is deterministic and keeps all state in memory; it opens no files or connections and needs no external cleanup. It verifies selected result values, exception type and parameter name, and rejection of the deliberately swallowed exception. It does not prove every string is handled, test localized input, exercise a web endpoint, or reserve inventory. Stock can change after this check; an actual reservation needs its own atomic operation and failure contract.
For the underlying syntax, continue with Introduction to Exception Handling. For conversion basics, read How to Convert a String to an Int in C#. To extend parser coverage beyond these examples, use the deterministic parsing-property harness.