Tuesday, December 19, 2017

Why would I use a closure to make an assignment to a Func or Action in C# when I can just use the equals sign?

Well, I am glad that you asked! In looking over this, this, this, and this it became obvious to me today that the gain is one of shapeshifting. Instead of having a Func or Action with one or more inbound properties you may just have an Action without any angle brackets (takes nothing, returns void) and a Func with just one type (the return type). Whatever inbound properties might be are specified right then upon the closure assignment. In effect, the gun is loaded and you'll just pull the trigger later without worrying then about what kind of ammunition it has. Bad analogy? This does not allow you to react to real time conditions with input types later on downstream the way a Func or Action typically might. Instead of making a game plan for how to react to things "tomorrow" you are making a timebomb for "tomorrow" so to speak. I guess you can always stamp overtop of the assignment with another assignment before you use the Func or Action with a terse signature if you need to alter plans. Bonus: Did you know a Func<bool> may have a closure return type like foo==bar or some other form of comparison?

No comments:

Post a Comment