One of my friend Kritul Rathod had gave his understanding of Action keyword in C#.
Passing the functions as parameters helps in many ways, here are basic ones
- It helps separate the coding logic (for some trivial things like exception handing, type conversions, Verbose Logging, etc – the things that clutters the code) from the actual class implementation.
- Since the ‘Actual Function Implementation’ stays in the same class, only its invocation logic is delegated to a separate class. so there is no need to pass a “Train” of arguments in function calls hence less future code changes .
To explain the logic behind the exception handling just have a look at the following code.
Class A { int i; int j; function Add(int arg1, int arg2) { try{ return arg1 + arg1; } catch(Exception e){ { Log(e.Message); } finally { //Do some funky stuff here; } } function Sub(int arg1, int arg2) { try{ return arg1 - arg1; } catch(Exception e){ Log(e.Message); } finally{ //Do some funky stuff here; } } }
Now for some great reason let’s say we make change to the Log method and pass one extra for passing actual exception object. We would need to do change in all classes using this method.
Please read part 2 of this post here.
1 comment