public static void Validate([AssertionCondition(AssertionConditionType.IS_NOT_NULL)][CanBeNull][ValidatedNotNull] this string value, [InvokerParameterName][NotNull] string argumentName, StringIs validationType) { if (ReferenceEquals(value, null)) { if (validationType.HasFlag(StringIs.NotNull)) { throw new ArgumentNullException(argumentName, ErrorMessages.ArgumentNull(argumentName)); } // It's null, so we can't validate the other conditions. return; } if (string.IsNullOrWhiteSpace(value)) { if (value.Length <= 0) { if (validationType.HasFlag(StringIs.NotEmpty)) { throw new ArgumentException(ErrorMessages.ArgumentZeroLengthString(argumentName), argumentName); } } else { if (validationType.HasFlag(StringIs.NotWhiteSpace)) { throw new ArgumentException(ErrorMessages.ArgumentWhiteSpaceString(argumentName), argumentName); } } } }
public static void Validate([AssertionCondition(AssertionConditionType.IS_NOT_NULL)][ValidatedNotNull] this string argumentValue, [NotNull][InvokerParameterName] string argumentName, StringIs validation) { /* * We should test "validation", but that would be an expensive thing to do for something that could be * called very frequently. */ var isNull = ReferenceEquals(argumentValue, null); if (validation.HasFlag(StringIs.NotNull) && isNull) { var normalizedArgumentName = string.IsNullOrWhiteSpace(argumentName) ? Exceptions.Fragment_UnknownArgument : argumentName; throw new ArgumentNullException(normalizedArgumentName, string.Format(CultureInfo.CurrentCulture, Exceptions.Validate_ArgumentIsNull, normalizedArgumentName)); } if (validation.HasFlag(StringIs.NotEmpty) && !isNull && argumentValue.Length <= 0) { var normalizedArgumentName = string.IsNullOrWhiteSpace(argumentName) ? Exceptions.Fragment_UnknownArgument : argumentName; throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Exceptions.Validate_ArgumentIsZeroLength, normalizedArgumentName), normalizedArgumentName); } #pragma warning disable S2583 // Conditionally executed blocks should be reachable if (validation.HasFlag(StringIs.NotWhiteSpace) && !isNull && argumentValue.Length > 0 && string.IsNullOrWhiteSpace(argumentValue)) #pragma warning restore S2583 // Conditionally executed blocks should be reachable { var normalizedArgumentName = string.IsNullOrWhiteSpace(argumentName) ? Exceptions.Fragment_UnknownArgument : argumentName; throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Exceptions.Validate_ArgumentIsWhiteSpaceOnly, normalizedArgumentName), normalizedArgumentName); } Contract.EndContractBlock(); }