An enum is best practice to give internal constants to readable string format, example
It’s very handy to use string rather to remember int value and it also helps to maintain code if down the road we need to change integer value it wont be difficult. I am sure developer knows very well about how to use enum in their code.
The post is all about answering few question comes while development or requirement, How you pass multiple value by using enum? or How to assign multiple enum values to variable? or How can I store combination of enum values using single enum variable?
All question have single answer, to use enum as bit flags. In order to achieve this, you have to add new attribute Flags to your enum declaration. As these values are bit you can use bitwise operation which are AND, OR, XOR and NOT.
Let’s see useful example of Flag enum using normal coding and then we will see same thing using Flags.
In normal coding if I want to calculate discount for four country and more then one at same time, I rather create for methods and call four individual functions
OR I can add bool into signature for calculating particular discount.
Drawback of first method is you have to keep adding new functions if you introduce new country and in second you have to pass false to country which you don’t want to do calculation, so signature will get increase in case we have more countries
Now lets use Flag enumeration to avoid mention drawbacks.
This will how your new enum will look like
A new attribute called Flags is added and we have assigned constants in power or TWO, that is 1,2,4,8 and so on, so when we use in combination no one get overlap.
Lets go ahead and create CalculateDiscount function and use into our program.
So single function CalculateDiscount is responsible to calculate discount for four different country at a time. If I want to calculate discount for German and Canada, you can do that by passing both in single argument using ‘|’ operator, its bitwise OR operator. You can use ‘&’ bitwise AND operator to determine whether a specific flag is set or not.
1 comment:
Great blog this helped me a lot.
Post a Comment