How will you make a combination of the Enum values in C# ? Explain with an example.

 Posted by Niladri.Biswas on 7/18/2012 | Category: C# Interview questions | Views: 1522 | Points: 40
Answer:

In C#, we have to decorate the Enum with Flag attribute and use a bitwise operator to make a combination of the values.

Let us look at the below example

class Program

{
static void Main(string[] args)
{
Console.WriteLine(Fruits.AllFruits.HasFlag(Fruits.Guava));
Console.ReadKey();

}

[Flags]
enum Fruits
{
Apple = 1,
Mango = 2,
Banana = 3,
Guava = 4,
AllFruits = Apple | Mango | Banana | Guava,
AppleANDGuava = Apple & Guava
}

}

/* Result */
True


We are checking if the Guava is present in the "AllFruits" enum.


Source: http://msdn.microsoft.com/en-u | Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response