Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does adding enum values break binary compatibility?

Imagine this enum in a DLL.

public enum Colors
{
    Red,
    Green
}

Does adding enum values break binary compatibility? If I were to change it, would existing EXEs break?

public enum Colors
{
    Red,
    Green,
    Blue
}

I saw this answer, but it seemed to address the case of inserting a value. If I add values to the end only, is that OK?

like image 601
TheBuzzSaw Avatar asked Oct 03 '12 20:10

TheBuzzSaw


2 Answers

No, this doesn't break binary compatibility (in as much as: the assembly will still load etc), because enums are basically integer literal constants. Inserting values in the middle is obviously a really dangerous idea, but you've already excluded that.

However, it can cause a number of other issues that you need to guard against:

  • some code (switch statements in particular) may not anticipate the new values; technically this was an issue before too, since enums are not value-checked (enum variables can contain undefined values)
  • anything that queries the available enums is going to get different results
    • in particular, serialization and deserialization may fail unexpectedly if there is data using enums that aren't yet expected by the particular client
like image 90
Marc Gravell Avatar answered Sep 21 '22 13:09

Marc Gravell


It should be fine, assuming you only append to the end. However, the risk of breaking would come from the fact that the enum values are implicitly defined, starting at 0. So if someone is persisting the values to a DB, you risk changing which values they map to.

As an example, if you changed your enum to be:

public enum Colors
{
    Blue,
    Red,
    Green
}

Anyone who stored these values in their DBs would see that things that were once Red, are now Blue, and what was Green is now Red.

Ideally, you should define your enum like so:

public enum Colors
{
    Red = 0,
    Green = 1
}

And then, when you add a new one, you should have:

public enum Colors
{
    Red = 0,
    Green = 1,
    Blue = 2
}

This will help prevent any potential versioning issues.

like image 38
Jeffrey Lott Avatar answered Sep 19 '22 13:09

Jeffrey Lott