0

I am facing the issue of validating a property whose validation properties are associated with the corresponding field name.

int _myIntField;
public int MyIntField {
    get { return _myIntField; }
    set { _myIntField = value; }
}

Now, when validating a Binding Object, I have access to the BindingField, which returns the property name MyIntField, not the field name _myIntField.

Is it possible to somehow retrieve _myIntField for the property? If so, how?

BogadoDiego
  • 329
  • 3
  • 7
neggenbe
  • 1,697
  • 2
  • 24
  • 62
  • 1
    Well if you naming convention is solid, you could just do a replace on the first letter... `string name = "_" + Char.ToLowerInvariant(input[0]) + input.Substring(1);` – musefan Aug 05 '16 at 14:55
  • 1
    You might could go Roslyn on it. As for a from-the-factory way of doing it, consider the following: `int Foo { get { return _bar * _baz > 0 ? _pete : _barney; } }`. What's the field for `Foo`? You may choose to write code that makes one assumption or another about that question, but there's no way the .NET framework can make any assumption that's meaningful or useful for everybody. – 15ee8f99-57ff-4f92-890c-b56153 Aug 05 '16 at 14:59
  • Possible duplicate of [How to get Getter backing field from PropertyInfo?](http://stackoverflow.com/questions/38490739/how-to-get-getter-backing-field-from-propertyinfo) – thehennyy Aug 05 '16 at 20:00

1 Answers1

0

Actually, for my case, I have a work-around: I created a custom attribute taking the associated field name as a parameter...

int _myIntField;
[MyAttribue("_myIntField")] 
public int MyIntField {
    get { return _myIntField; }
    set { _myIntField = value; }
}

For the sake of completeness, here is the attribute's declaration:

public class MyAttribue : ValidationAttribute {
    protected readonly string _fieldName;

    public MyAttribue(string fldName) {
      _fieldName = fldName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
      if (validationContext == null) {
        return ValidationResult.Success;
      }
      ErrorMessage = string.Empty;

      if (validationContext.ObjectInstance != null) {
        // do whathever validation is required using _fieldName...
      }
      //
      if (!string.IsNullOrWhiteSpace(ErrorMessage)) {
        return new ValidationResult(ErrorMessage);
      }
      return ValidationResult.Success;
    }
  }
neggenbe
  • 1,697
  • 2
  • 24
  • 62