Question Strange code, why doesn't the compiler give an error and what could the use

Marc W

Member
Joined
Oct 8, 2014
Messages
8
Programming Experience
Beginner
I am encountering some strange old code:
foreach (OrgType type in Enum.GetValues(typeof(OrgRType)))
{
    // ...
}

I thought that the two Types here (OrgType and OrgRType) should be the same, and even if it does compile, I fail to see the use. You are looping over the wrong enum type right?
 
Last edited:
That is dodgy code but it should still run, assuming that OrgType has a value that corresponds to each OrgRType value. Enumerations are just numbers under the hood, so you can cast between different types.
 
Thanks. One more question. If I understand that it are integers under the hood, this would mean that the actual strings used in the enumerations are irrelevant, right? So if OrgType has the members A, B, C, and OrgRType the members C, B, A (in that order) it maps. But A 'goes to' C, since the integer numbers of the enums equal. I am pretty sure this is the case, I shall make a little test of it too.
 
Thanks. One more question. If I understand that it are integers under the hood, this would mean that the actual strings used in the enumerations are irrelevant, right? So if OrgType has the members A, B, C, and OrgRType the members C, B, A (in that order) it maps. But A 'goes to' C, since the integer numbers of the enums equal. I am pretty sure this is the case, I shall make a little test of it too.

That is correct. Enumerations are designed to be friendly to the developer, hence the text labels for each value that should be meaningful names, but efficient to the system, hence they are stored simply as numbers. By default, the first value in an enumeration is assigned the number 0 and each other value is 1 more then its predecessor. As such, in your example, OrgType.A would have the value 0 and, if you converted that to an OrgRType value you would get OrgRType.C. That's a perfect example of why that code you posted in the first post, while legal, is bad.
 
Back
Top Bottom