I want to create a generic validation class, so I can do something like:
Validation v = new Validation();
v.AddRequired(x => this.Name);
v.AddRange(x => x.this.Age, 5, 65);
I'm unsure as to how to write the method definition and make the evaluation?
Where AddRequired
would take a string
and AddRange
would take a numeric type (int
, primarily but also double
, decimal
, etc)
Make
Validation
generic on the type ofx
, define methods takingFunc<x,object>
or some other type as needed, store these functions, and call them from theValidate(x)
method:This implementation is very skeletal - it needs null checks in many places to be useful. In addition, it's not very efficient, because
IComparable
andobject
could wrap value types. However, the way of passing and storingFunc<T,...>
objects should give you an idea of how to implement the rest of it.An approach would be:
This would just store your conditions in
List<T>
's. You then would have to add a method to yourValidation
class to evaluate the expressions:Then use like this:
There should be some libraries available for this task. However, you can get some experience with lambdas by writing this yourself. I have made a draft implementation for the
AddRange
, I hope you can go further from here.