Articles → .NET → Flags Attribute In Enums C#

Flags Attribute In Enums C#






Software Requirement





Technical Knowledge




  1. Basics of C#
  2. What are enums?
  3. How to create, compile and execute project using visual studio?
  4. What is the purpose of Flags attribute?
  5. Adding Flags attribute on enums means that enumerations will be treated as bit field.

Syntax


[Flags]
public enum Enum_Name {}



Example




  1. Above 18 years of age.
  2. A resident of that country
  3. A graduate
  4. Without criminal background.


public bool IsEligibleToContestElection(bool above18, bool resident, bool graduate, bool nocriminalbackground) {
  if (above18 == true && resident == true && graduate == true && nocriminalbackground == true) return true;
  else return false;
}




IsEligibleToContestElection(true, true, true, true)






[Flags]
public enum EligibilityCriteria {
  Above18,
  IsResident,
  AGraduate,
  NoCriminalBackground
}

public bool IsEligibleToContestElection(EligibilityCriteria criteria) {
  if (criteria == (EligibilityCriteria.Above18 & EligibilityCriteria.IsResident & EligibilityCriteria.AGraduate & EligibilityCriteria.NoCriminalBackground)) return true;
  else return false;
}




IsEligibleToContestElection(EligibilityCriteria.Above18 & EligibilityCriteria.IsResident & EligibilityCriteria.AGraduate & EligibilityCriteria.NoCriminalBackground)





Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, October 29, 2014

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250