1
Vote

Use reflection to determine the argument name.

description

Current:
If no name is provided when using Requires, a generic name "value" is supplied.

Proposal:
If no name is provided when using Requires, use Reflection to look up the argument's name.

comments

robbratton wrote Apr 21, 2015 at 3:42 PM

Here's the workaround I'm considering. It's not too bad.
public static void String1(string arg)
{
    Condition.Requires(arg, MemberInfoGetting.GetMemberName(() => arg))
        .IsNotNullOrWhiteSpace()
        .IsNotShorterThan(10)
        .IsNotLongerThan(15)
        ;

    Debug.WriteLine(arg);

}

//
public static class MemberInfoGetting
{
    public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
    {
        MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
        return expressionBody.Member.Name;
    }
}
Source of MemberInfoGetting

dot_NET_Junkie wrote Apr 21, 2015 at 3:49 PM

This design has been discussed before here: https://www.codeproject.com/Articles/27850/CuttingEdge-Conditions?msg=2640907#xx2640907xx. In that discussion I explain why I am against doing this.

C# 6 contains a feature that makes this cleaner:
Condition.Requires(arg, nameof(arg))