C# program to demonstrate the Flags Attribute

Here, we are going to demonstrate the Flags Attribute in C#?
Submitted by Nidhi, on November 01, 2020

Here, we will demonstrate the Flags attribute. The Flags attribute is used to specify enum constants that can be set with bitwise operators.

Program:

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 »


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.