1

i want to pass a property as a parameter to another property custom attribute but i can't because its not static Model ex :

public class model1
{
     public DateTime param1 { get; set; }
     [CustomAttribute (param1)]
     public string param2 { get; set; }
}

public class CustomAttribute : ValidationAttribute
{
    private readonly DateTime _Date;
    public CustomAttribute(DateTime date)
    {
        _Date= date;
    }
}

because i want to make a custom validation between this two attributes .

1 Answers1

0

Attributes are not stored as executable code, so there are significant limitations on the kind of data you can include in them.

Basically, you must stick with base types: strings, numbers, dates. Everything that can be a constant.

Fortunately, you can use a bit of reflection and the nameof operator:

public class model1
{
     public DateTime param1 { get; set; }
     [CustomAttribute (nameof(param1))]
     public string param2 { get; set; }
}

public class CustomAttribute : ValidationAttribute
{
    private readonly string _propertyName;
    public CustomAttribute(string propertyName)
    {
        _propertyName = propertyName;
    }
}

Keep in mind that the validation logic should reside outside the attribute's code.

The needed ingredients for the validation will be Type.GetProperties, PropertyInfo.GetValue, and MemberInfo.GetCustomAttribute.

If you need a complete example and care to better explain the use case, let me know.

Alberto Chiesa
  • 7,022
  • 2
  • 26
  • 53
  • Then, if your problem is solved, upvote the answer (with the up arrow) and accept it as the proper answer (selecting the green mark). – Alberto Chiesa Nov 29 '18 at 11:24