Introduction
In C# enum is a named integer constant. But a type can have only one enum value. FlagsAttribute is used to assign multiple enum values.
Example
using System;
public class Program
{
public static void Main()
{
var rocky = new Person("Rock", Vehicle.BMWX5);
var peter = new Person("Peter Parker", Vehicle.Highlander);
rocky.PersonInfo();
//Output: Rock owns BMWX5
peter.PersonInfo();
//Output: Peter Parker owns Highlander
}
}
public class Person
{
public string Name{get;set;}
public Vehicle Vehicle{get;set;}
public Person(string name, Vehicle vehicle)
{
Name = name;
Vehicle=vehicle;
}
public void PersonInfo()
{
Console.WriteLine($"{Name} owns {Vehicle}");
}
}
public enum Vehicle
{
none=0,
BMWX5=1,
LandRover=2,
LincolnAviator=4,
Highlander=8
}
In the above program, one person can own one vehicle.
What if a person owns 2 or more vehicles. In this case FlagsAttribute is useful.
using System;
public class Program
{
public static void Main()
{
//vehicle2 is now represents 2 vehicles BMWX5 and Highlander both.
var vehicle2 = Vehicle.BMWX5|Vehicle.Highlander;
var rocky = new Person("Rock", Vehicle.BMWX5);
var peter = new Person("Peter Parker", Vehicle.Highlander);
// John owns vehicle2 means he has 2 vehicles.
var john = new Person("John", vehicle2);
rocky.PersonInfo();
peter.PersonInfo();
john.PersonInfo();
//Output: John owns BMWX5, Highlander
}
}
public class Person
{
public string Name{get;set;}
public Vehicle Vehicle{get;set;}
public Person(string name, Vehicle vehicle)
{
Name = name;
Vehicle=vehicle;
}
public void PersonInfo()
{
Console.WriteLine($"{Name} owns {Vehicle}");
}
}
[Flags]
public enum Vehicle
{
none=0,
BMWX5=1,
LandRover=2,
LincolnAviator=4,
Highlander=8
}
No comments:
Post a Comment