I created a simple class ArgumentValidator
to simplify the prerequisites of the argument in any given method. Most of them are null
either limitations, and it becomes quite tedious after a couple
if (arg == null ) throw new ArgumentNullException(nameof(arg));
So, I came up with the following setup:
public static class ArgumentValidator
{
public interface IArgument<T>
{
string ParamName { get; }
T Value { get; }
}
private class Argument<T>: IArgument<T>
{
public Argument(T argument, string paramName)
{
ParamName = paramName;
Value = argument;
}
public string ParamName { get; }
public T Value { get; }
}
public static IArgument<T> Validate<T>(this T argument, string paramName = null)
{
return new Argument<T>(argument, paramName ?? string.Empty);
}
public static IArgument<T> IsNotNull<T>(this IArgument<T> o)
{
if (ReferenceEquals(o.Value, null))
throw new ArgumentNullException(o.ParamName);
return o;
}
public static IArgument<T> IsSmallerThan<T, Q>(this IArgument<T> o, Q upperBound) where T : IComparable<Q> { ... }
}
And I can use it as follows:
public Bar Foo(object flob)
{
flob.Validate(nameof(flob)).IsNotNull().IsSmallerThan(flob.MaxValue);
}
Ideally, I would like to get rid of nameof(flob)
the call Validate
and eventually get rid of Validate
alltogether; the sole purpose Validate
is to not skip the nameof(...)
circuit every time you check.
Is there a way to get the name flob
inside the method Validate()
?
source
share