How to get and modify a property value through a custom Attribute?

Posted by David G on Stack Overflow See other posts from Stack Overflow or by David G
Published on 2010-05-19T09:41:40Z Indexed on 2010/05/19 9:50 UTC
Read the original article Hit count: 154

Filed under:
|

I want to create a custom attribute that can be used on a property like:

[TrimInputString]
public string FirstName { get; set; }

that will be functional equivalent of

private string _firstName
public string FirstName {
  set {
    _firstName = value.Trim();
  }
  get {
    return _firstName;
  }
}

So basically every time property is set the value will be trimmed.

How do I get the value parsed, modify that value and then set the property with the new value all from within the attribute?

[AttributeUsage(AttributeTargets.Property)]
public class TrimInputAttribute : Attribute {

  public TrimInputAttribute() {
    //not sure how to get and modify the property here
  }

}

© Stack Overflow or respective owner

Related posts about c#

Related posts about asp.net-mvc