Runtime: Proposal: Enums should implement generic IEquatable/IComparable interfaces

Created on 31 May 2016  路  5Comments  路  Source: dotnet/runtime

Every enum should implement its own version of IEquatable<T> and IComparable<T>, to avoid boxing when being compared/tested for equality (as they are really just ints underneath). The API would be similar to how each delegate class has its own version of Invoke/each T[] implements IList<T>, although there is no strongly-typed base class that actually declares this.

(Note: I'm aware that EqualityComparer<T>.Default already specializes for enums, however I still think this would be an API addition worth pursuing. Additionally, Comparer<T>.Default does not specialize for enums and falls back to boxing.)

Enums already implement the non-generic IComparable interface (there is no non-generic IEquatable), so I think this would be a welcome change right?

api-needs-work area-System.Runtime

Most helpful comment

@omariom Maybe we can let users choose to only implement the interface if they want to:

public enum MyEnum : byte, IEquatable<MyEnum> {}

All 5 comments

When I found why EqualittyComparer is specialized for enums I got the same idea. But then I realized that it would be too many repeating and yet rarely used methods. It will just increase the size of assemblies.

@omariom Maybe we can let users choose to only implement the interface if they want to:

public enum MyEnum : byte, IEquatable<MyEnum> {}

We need a formal API proposal for this that also covers use cases.

I've got a good use case for this. I have a class which represents a code pragma. This pragma defines the policy for assertions, whether they are checked or not, basically. The pragma may be defined either globally, or with a set of policies. The representing class can contain only one or the other, combining both policy definitions is completely invalid in the language.

The global policy value is simply an enumeration of the possible values. With this in mind, it makes sense to be able to equate the representing class and the constituent enumeration. Currently I'd have to work around this with implicit/explicit conversions, but I think you can see the issue with that approach (rather extreme boxing, to say the least).

I should further add, while I can of course define IEquatable<PolicyIdentifier> for the representing class, this only enables .Equals() to be called in "one direction". Because this direction is the "wrong way" for certain operations like unit test assertions, equality can not be defined in the "direction" it is most needed.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bencz picture bencz  路  3Comments

btecu picture btecu  路  3Comments

jamesqo picture jamesqo  路  3Comments

EgorBo picture EgorBo  路  3Comments

v0l picture v0l  路  3Comments