Skip to content

Guard Method Examples

Chris Dahlberg edited this page Mar 19, 2019 · 1 revision

The Guard class provides various methods for validating arguments and object state. For most methods, the value being validated will also be returned from the method.

// The ArgumentIsNotNull method will throw an ArgumentNullException if the value is null
_pocoValue = Guard.ArgumentIsNotNull(nameof(pocoArgument), pocoArgument);

// ArgumentIsNotNegative, ArgumentIsPositive, and ArgumentIsWithinRange methods will throw an
// ArgumentOutOfRangeException if the value is not within the acceptable range
_intValue = Guard.ArgumentIsNotNegative(nameof(intArgument), intArgument);
_intValue = Guard.ArgumentIsPositive(nameof(intArgument), intArgument);
_intValue = Guard.ArgumentIsWithinRange(nameof(intArgument), intArgument, 0, 255);

// ArgumentIsNotNullOrEmpty will throw an ArgumentNullException if the string value is null or an
// ArgumentException if the string is empty or whitespace
_stringValue = Guard.ArgumentIsNotNullOrEmpty(nameof(stringArgument), stringArgument);
_stringValue = Guard.ArgumentIsNotNullOrWhiteSpace(nameof(stringArgument), stringArgument);

// ArgumentIsValid will throw an ArgumentException if the flag passed in is false
Guard.ArgumentIsValid(nameof(pocoArgument), pocoArgument.Name.Length < 100);
_pocoValue = Guard.ArgumentIsValid(nameof(pocoArgument), pocoArgument.Name.Length < 100, pocoArgument);

// ObjectHasNotBeenDisposed will throw an ObjectDisposedException if the flag passed in is true
Guard.ObjectHasNotBeenDisposed(disposable, _hasDisposableBeenDisposed);

// OperationIsValid will throw an InvalidOperationException if the flag passed in is false
Guard.OperationIsValid(_isConnected);

Clone this wiki locally