I have enums in one of my windows application like below:
private enum ModificationType
{
Insert = 0,
Update = 1,
Delete = 2
}
I have below function:
private void UpdateDatabaseTransactions(ModificationType _modifcationType)
{
int modType = (int)_modifcationType;
if (modType == 0) {...}
if (modType == 1) {...}
if (modType == 2) {...}
also I can use it like below:
if (_modifcationType == ModificationType.Insert) {...}
if (_modifcationType == ModificationType.Update) {...}
if (_modifcationType == ModificationType.Delete) {...}
}
What is the difference between the both and in which scenarios I have to typecast the value and use, is there any performance boosters in using any one of the above, or both are same?
What happens when you decide to change the
ModificationTypeenum later? For example:This is, admittedly, a contrived example. (But certainly not impossible – assume your
enumis used to reference some external dependency that introduces a breaking change, say a C API.)But if you refer to these enum types by value, you’ll have to track down all references of them. Do you want to go trawling through your code trying to figure out if the number 3 is used to reference that enum or some other random constant?
Instead, you should use
ModificationType.Deleteso that you don’t have to worry about these issues. That’s why theenumtype exists, after all.There is no performance penalty for using
ModificationType.Deleteinstead of 4, 5, 6 or whatever it might happen to be.