Comparing structs for equality without boxing

大城市里の小女人 提交于 2019-12-01 16:46:41
MicroVirus
  1. The first of the following methods is illegal since structs do not implicitly override the equality operators ==/!=.

True.

  1. The second "appears" to avoid boxing.

The signature of the called method is EqualityComparer<T>.Equals(T,T) which uses the type T for the parameters, so it does not require boxing to call.

The implementation of the default comparer checks if T is IEquatable<T> and if so uses a comparer that uses IEquatable<T>.Equals and else uses a comparer for Object.Equals, so internally there might be boxing applied if the struct is not IEquatable ('only if needed').

  1. The third method should always box the struct since it's calling object.Equals(object o).

True.

  1. The fourth has both overloads available (object/T) so I'm assuming it will avoid boxing as well. However, the target struct would need to implement the IEquatable interface, making the helper extension method not very helpful.

Yes, it does not require boxing, as per this SO answer. This is the effective code you get for the specific case of T : IEquatable from the EqualityComparer<T>.Default.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!