0

I currently have a validation class with a method which validates that a string is not null (and logs the info, but that's not the concern here)

protected void ValidateStringNotEmpty(string propertyName, string value)
{
    if (string.IsNullOrWhiteSpace(value))
    {
        ValidationErrors.Add($"Property [{propertyName}] must be filled");
    }
}

which is called using

ValidateStringNotEmpty(nameof(Name), Name);

Is there an easy (and optimized) way to prevent the need to pass the first argument nameof(property) ?

I saw solutions using the stacktrace to trace the call back, but it does not seem to be a great solution...

EDIT: What I'm really trying to do is see if something exists to do this (removing the need to pass the name of the argument). I know the pragmatic solution is the one I already use, and this is not a problem.

Shimrod
  • 3,115
  • 2
  • 36
  • 56
  • Does this answer your question? [ArgumentNullException - how to simplify?](https://stackoverflow.com/questions/12043875/argumentnullexception-how-to-simplify) – Orel Eraki Feb 26 '20 at 21:35
  • Is that the question they're asking? – Robert Harvey Feb 26 '20 at 21:36
  • https://social.msdn.microsoft.com/Forums/vstudio/en-US/69cce588-006e-4331-ac34-21967845ab34/pass-a-c-property-name-as-a-parameter-to-an-utility-class-method?forum=csharpgeneral – Robert Harvey Feb 26 '20 at 21:39
  • You can use expression trees with a lambda expression, but they're brittle and not at all "easy". –  Feb 26 '20 at 21:39
  • @OrelEraki I guess the accepted answer could work but seems a bit of overkill (I'm only trying to only need to pass 1 argument, this solution seems so heavy !) – Shimrod Feb 26 '20 at 21:45
  • @Amy IIRC I saw a solution with lambda, but it was sait it uses an undocumented feature which could be removed/fixed in the future – Shimrod Feb 26 '20 at 21:47
  • @Shimrod ??? I'm not sure what undocumented feature you're referring to. The accepted answer you just referred to is along the lines of what I meant with expression trees. I use expression trees and lambdas in my own code. The only reason I haven't written such an answer is because I hardly consider it "easy". –  Feb 26 '20 at 21:48
  • @Amy I can't find back the article. But I agree with you it's not easy, considering I only want to remove a `nameof(parameter)`. It's really just to know if there is some magical thing I don't know, the extra characters to type don't kill me at all :-) – Shimrod Feb 26 '20 at 22:05

2 Answers2

1

There is now "CallerArgumentExpression" that has shipped with dotnet 6 / C# 10 and doing exactly what you're looking for

protected void ValidateStringNotEmpty(string value, [CallerArgumentExpression("value")] string propertyName = "")
kipy
  • 527
  • 4
  • 10
0

What about validating directly inside the property and leveraging [CallerMemberName] ?

private string _text;

public string Text
{
    get => _text;
    set
    {
        if (IsValid(value))
        {
            _text = value;
        }
        else
        {
            ValidationErrors.Add("'abcd' was expected.");
        }
    }
}

private bool IsValid<T>(T value, [CallerMemberName] string propertyName = null)
{
    switch (propertyName)
    {
        case nameof(Text):
            return value as string == "abcd";
        default:
            throw new ArgumentOutOfRangeException(nameof(propertyName), propertyName, null);
    }
}

public static class ValidationErrors
{
    public static void Add(string message, [CallerMemberName] string propertyName = null)
    {
        throw new NotImplementedException();
    }
}
aybe
  • 15,516
  • 9
  • 57
  • 105
  • while this solution is elegent, I don't want the validation to be triggered at each value change, only when I call it. Thanks ! (The downvote is not mine btw...) – Shimrod Feb 26 '20 at 21:55
  • I don't know if you're using WPF, but it allows to trigger a validation only when, for instance, control loses focus as opposed to whenever the property has changed: https://learn.microsoft.com/en-us/dotnet/api/system.windows.data.updatesourcetrigger?view=netframework-4.8. – aybe Feb 26 '20 at 21:58
  • No, it's in a simple class library, no link to GUI or whatever – Shimrod Feb 26 '20 at 22:04
  • Setting an invalid value, then setting a valid value, does not clear the validation error(s). –  Feb 26 '20 at 22:05
  • That was just an example, of course in real there is much more to do. – aybe Feb 26 '20 at 22:57