What does applying [Flags] really do?
I know it modifies the behavior of Enum.ToString, but does it do anything else? (e.g. Different compiler or runtime behavior, e
Flags gives an option to use enum for multiple value.
Consider a situation where you want to use Checkboxes for different situation but you do not want to create different columns in the database. If you have 20 check boxes you will have to create 20 columns in the database with bool. But with flags you can create one column and use that value to store in the column. Run this example in the console to understand it better.
class Program
{
static void Main(string[] args)
{
//Set the features that you require for car. Consider it as checked in the UI.
CarFeatures carFeatures = CarFeatures.AC | CarFeatures.Autopilot| CarFeatures.Sunroof;
//Do the backend logic
if (carFeatures.HasFlag(CarFeatures.Autopilot))
{
//Show Autopilot cars
}
//See the what carfeatures are required
Console.WriteLine(carFeatures);
//See the integer value of the carfeatures
Console.WriteLine((int)carFeatures);
Console.ReadLine();
}
}
[Flags]
public enum CarFeatures
{
AC=1,
HeatedSeats= 2,
Sunroof= 4,
Autopilot= 8,
}
The different combination always gives you a unique number which c# tracks back to find what all are marked.