Sometimes we would like to use an enum as a set of flags, so we can set several "states" of the same property to a combined state of several values. Let's see an example. Imagine we have the following enum class:
public enum ExportTypes
{
Text,
Excel,
CSV,
JSon,
XML
}
So, we have a set of types of exportations for something in our program. Now, this enum would only allow us to have a single export type. Perhaps we would like two, or three, or all of them. Should we run the program several times? Should we add a single property for each type of import and make it boolean?
A better option would be to say something like "Export text AND excel". How can we accomplish that with an enum? We just need to add the FlagsAttribute as a decorator for this enum class.
[Flags]
public enum ExportTypes
{
None,
Excel,
CSV,
JSon,
XML,
Text,
}
Now, we can use the bitwise operator OR to add several values of the same enum. For example, imagine the following class that receives the enum values in one of it's properties.
ExportExecution.ExportTypes = ExportTypes.Text | ExportTypes.Excel;
Now, the problem is not writing to this property, but reading from it. Let's suppose that we have a method called "Export" that has a bifurcation when the export type is Text. We just have to use the bitwise operator AND to find out if the Text value is set to the property. Check the following example.
if(this.ExportTypes & ExportTypes.Text == ExportTypes.Text) {
This would check that the Text property is contained within the values set. This is a very bad explanation, but Im saving it for later, so I could explain this first to you.
Now you know how to create and use a bit flag enum class. But, what the hell just happened? Why does it work? It is important to understand this, otherwise you may end up being a mindless programmer building a trench in a crappy job believing you can be better than that. Ok, maybe that's a small exageration.
Basically, what you have is the following values.
public enum ExportTypes
{
None = 0
Excel = 1
CSV = 2
JSon = 4
XML = 8
Text = 16
}
They all scale in the potency of 2, because bit enconding has 2 values. So, let's say you want Excel and JSon. That would be like 1 + 4 or 0101. You see? each enum value is a 1.
0000000 is nothing
0000001 is excel
0000010 is CSV
0000011 is excel and CSV
Now, a last hint. The first value will be ZERO so it is always TRUE. This should never be a value where you ask for it being false, since it will always be present.
No hay comentarios:
Publicar un comentario