Advantages/Disadvantages of different implementations for Comparing Objects

后端 未结 5 593
滥情空心
滥情空心 2021-02-05 09:27

This questions involves 2 different implementations of essentially the same code.

First, using delegate to create a Comparison method that can be used as a parameter whe

5条回答
  •  爱一瞬间的悲伤
    2021-02-05 09:51

    The delegate technique is very short (lambda expressions might be even shorter), so if shorter code is your goal, then this is an advantage.

    However, implementing the IComparer (and its generic equivalent) makes your code more testable: you can add some unit testing to your comparing class/method.

    Furthermore, you can reuse your comparer implementation when composing two or more comparers and combining them as a new comparer. Code reuse with anonymous delegates is harder to achieve.

    So, to sum it up:

    Anonymous Delegates: shorter (and perhaps cleaner) code

    Explicit Implementation: testability and code reuse.

提交回复
热议问题