Well, just if you have an Entity class and you want to use lambda expressions for that Entity to determine if something is really (returning a boolean value), you can use Func.
So, given Entity:
class Entity { public string MyProperty { get; set; } }
You can define a ValidationRule class for this:
class ValidationRule<T> where T : Entity { private Func<T, bool> _rule; public ValidationRule(Func<T, bool> rule) { _rule = rule; } public bool IsValid(T entity) { return _rule(entity); } }
Then you can use it as follows:
var myEntity = new Entity() { MyProperty = "Hello World" }; var rule = new ValidationRule<Entity>(entity => entity.MyProperty == "Hello World"); var valid = rule.IsValid(myEntity);
Of course, this is only one possible solution.
If you remove the general restriction above ("where T: Entity"), you can make this a universal rule engine that can be used with any POCO. You would not need to derive a class for each type of use that you need. Therefore, if I wanted to use the same class in a TextBox, I could use the following (after removing the general constraint):
var rule = new ValidationRule<TextBox>(tb => tb.Text.Length > 0); rule.IsValid(myTextBox);
It is quite flexible. Using lambda expressions and generics together is very great. Instead of accepting Func or Action, you can accept Expression> or Expression> and have direct access to the heap expression to automatically examine things like the name of a method or property, type of expression, etc. And people using your class would not have to change one line of code.
Jason olson
source share