12. January 2011 01:43
I ran across this today while refactoring/reviewing some code:
What in the heck I am I supposed to do with this? Delete it? Refactor it? Quickly close the file and pretend I never saw it? Mind you that it’s in code that’s in production and get’s run several times a day…and the code works as expected.
I chose to refactor it:
Unit tests pass:
Hold your breath!
4. November 2010 14:10
C# allows method group conversions, which simplify the invocation of delegates within your code. This is a feature that was added to C# 2.0 and when combined with the Linq extensions provided with .NET 3.5, you can drastically shorten and simplify code.
“Similar to the implicit anonymous method conversions described in §13.5, an implicit conversion exists from a method group (§14.1) to a compatible delegate type. If
D is a delegate type, and
E is an expression that is classified as a method group, then
D is compatible with
E if and only if
E contains at least one method that is applicable in its normal form (§184.108.40.206) to any argument list (§14.4.1) having types and modifiers matching the parameter types and modifiers of
Basically what the above means that the compiler is “smart” enough to infer the correct overload to call given that their is an adequate candidate method available. For example, given the following two methods:
First we can refactor the for loop using lambda expression and the Linq extensions:
Then simplify the lambda expression even further by substituting for the implicit method group conversion:
Note that the green squiggly lines are hints made by Resharper that the line of code can be refactored. If your not aware of Resharper, it’s a Visual Studio add on that turns VS from a Pinto to Ferrari! If you don’t believe me, try the free trial here. Ok, enough cool-aid and free marketing for resharper…
So, your probably thinking one of three things about now (assuming you made it this far):
- “Big fricken deal, he saved five lines of code”
- “Eh, old news. Moving on.”
- “Wow, that’s fricken awesome dude!”
Personally, I tend towards #3. I am a huge fan (obviously) of method group conversions because they reduce complexity. They simply make the code easier to read and digest. Code that is easier to read and digest is more easily maintained. Code that is easier to maintained, tends to be of higher quality and less error prone.