C# - Flags Attribute Example

Here, we will learn about the Flags attribute in C# with the help of example.
Submitted by Nidhi, on November 01, 2020 [Last updated : March 23, 2023]

Flags Attribute

The Flags attribute is used to specify enum constants that can be set with bitwise operators.

C# program to demonstrate the example of Flags Attribute

The source code to demonstrate the Flags attribute is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Program to demonstrate the FlagAttribute in C#

using System;

class Sample
{
    enum Weeks
    {
        Sun = 1, Mon = 2, Tue = 4, Wed = 8, 
    }


    [Flags]enum WeekFlags
    {
        Sun = 1, Mon = 2, Tue = 4, Wed = 8
    }

    // Main Method 
    public static void Main(string[] args)
    {
        Console.WriteLine((Weeks.Tue | Weeks.Wed).ToString());
        Console.WriteLine((WeekFlags.Tue | WeekFlags.Wed).ToString());
    }
}

Output

12
Tue, Wed
Press any key to continue . . .

Explanation

In the above program, we created a Sample class that contains two enumerations Weeks and WeekFlags. Here, WeekFlags enumeration is declared with Flags attribute. The Sample class also contains the Main() method. The Main() method is the entry point for the program.

Console.WriteLine((Weeks.Tue | Weeks.Wed).ToString());

The above statement will print 12 after performing bitwise or operation on the console screen.

Console.WriteLine((WeekFlags.Tue | WeekFlags.Wed).ToString());

The above statement will print "Tue, Wed" after performing bitwise or operation on the console screen because we used Flags attribute with WeekFlags enumeration.

C# Basic Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.