c# - Return from parent method inside of Action<string> -


i working inside of method performs series of validation checks , should of checks fail calls action<string> run common rejection code. set similar this:

public void validationmethod() {     action<string> rejectionroutine = (rejectiondescription) => {         // reject description         // other common code     };      if (condition != requiredvalue) {         rejectionroutine("condition check failed");         // have put `return` here following every failed check     }      // many more checks following } 

in system once 1 check has failed validation have no need validate rest, want run common rejection code inside action , exit method. return on next line following call rejectionroutine. i'm wondering if there's way can incorporate ability return or terminate execution of parent method inside action?

i know bit nit-picky feel better extensibility further down road if else needs add additional validation checks (they won't have concern putting return on place) encapsulating common behavior of ending execution inside of code supposed common these cases.

one way of cleaning code bit extrapolate of checks out collection:

dictionary<func<bool>, string> checks = new dictionary<func<bool>, string>() {     {()=> condition != requiredvalue, "condition check failed"},     {()=> othercondition != otherrequiredvalue, "other condition check failed"},     {()=> thirdcondition != thirdrequiredvalue, "third condition check failed"}, }; 

if it's important checks run in particular order (this code has unpredictable order) you'd want use list<tuple<func<bool>, string>> instead.

var checks = new list<tuple<func<bool>, string>>() {     tuple.create<func<bool>, string>(()=> condition != requiredvalue         , "condition check failed"),     tuple.create<func<bool>, string>(()=> othercondition != otherrequiredvalue         , "other condition check failed"),     tuple.create<func<bool>, string>(()=> thirdcondition != thirdrequiredvalue         , "third condition check failed"), }; 

you can use linq validation:

var failedcheck = checks.firstordefault(check => check.item1()); if (failedcheck != null)     rejectionroutine(failedcheck.item2); 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -