Why does addition require a cast but subtraction works without a cast? See the code below to understand what I am asking
public enum Stuff
{
A = 1,
B = 2,
C = 3
}
var resultSub = Stuff.A - Stuff.B; // Compiles
var resultAdd = Stuff.A + Stuff.B; // Does not compile
var resultAdd2 = (int)Stuff.A + Stuff.B; // Compiles
note: For both addition and subtraction it does not matter whether result is out of range (of the enum) or not in all three examples above.
Good question – I was surprised that the first and third lines worked.
However, they are supported in the C# language specification – in section 7.8.4, it talks about enumeration addition:
And in section 7.8.5:
So that’s why the compiler behaves like that – because it’s what the C# spec says to do 🙂
I wasn’t aware that any of these operators exist, and I’ve never knowingly seen them used. I suspect the reasons for their existence are buried somewhere in the language design meeting notes that Eric Lippert occasionally dives into – but I also wouldn’t be surprised if they were regretted as adding features for little benefit. Then again, maybe they’re really useful in some situations 🙂