How can I write a custom attribute that targets whatever property it is attached to and that checks the logic of the boolean expression?
If the check is false I want the setter method to fail.
Example implementation:
public class CheckAttribute : Attribute
{
public CheckAttribute(int checkvalue, Operation op)
{
int val = 0;
System.Linq.Expressions.Expression exp = System.Linq.Expressions.Expression.Condition(op switch
{
Operation.Equals => System.Linq.Expressions.Expression.Constant(val == checkvalue),
Operation.GtrThan => System.Linq.Expressions.Expression.Constant(val > checkvalue),
Operation.LssThan => System.Linq.Expressions.Expression.Constant(val < checkvalue),
Operation.GrtOrEquals => System.Linq.Expressions.Expression.Constant(val >= checkvalue),
Operation.LssOrEquals => System.Linq.Expressions.Expression.Constant(val <= checkvalue),
Operation.Neq => System.Linq.Expressions.Expression.Constant(val != checkvalue),
_ => throw new InvalidOperationException()
},
System.Linq.Expressions.Expression.Constant(true),
System.Linq.Expressions.Expression.Constant(false));
if (!System.Linq.Expressions.Expression.Lambda<Func<bool>>(exp).Compile()())
{
throw new InvalidOperationException("Check condition fails");
};
}
}
usage:
class MyClass
{
[CheckAttribute(0, CheckAttribute.Operation.LssThan)]
public int MinValue { get; set; }
[CheckAttribute(10, CheckAttribute.Operation.GtrThan)]
public int MaxValue { get; set; }
}
If any code instantiates MyClass and sets MinValue to a value less than 0, I want an exception at runtime.
Similarly, if any code instantiates MyClass and sets MaxValue to a value greaer than 10, I want an exception.
It would be excelent if exception could be thrown at compile time, but I suppose it would need some magic with System.Runtime.CompileServices, if that's even possible.
In short, I want to write a custom attribute which constrains property values on assignment via the setter method, and not explicity code logic to every setter property to check the attribute value.
This is not a job for an attribute. Attributes do not cause any logic to fire by themselves, they're just metadata. Some other code has to read the attribute and react to it.
So with an attribute you could only have an external validator that would check the values of the properties after the fact and then threw an exception.
SharpLab link.