Enum.HasFlag method in C# 4.0

Posted By  jalpesh On 01 Jan 2011 07:01:00
emailbookmarkadd commentsprint
No of Views:791
Bookmarked:0 times
Votes:0 times

Introduction

Enums in dot net programming is a great facility and we all used it to increase code readability. In earlier version of .NET framework we don’t have any method anything that will check whether a value is assigned to it or not. In C# 4.0 we have new static method called HasFlag which will check that particular value is assigned or not. Let’s take an example for that. First I have created a enum called PaymentType which could have two values Credit Card or Debit Card. Just like following.

public enum PaymentType
{
   DebitCard=1,
   CreditCard=2
}

Now We are going to assigned one of the value to this enum instance and then with the help of HasFlag method we are going to check whether particular value is assigned to enum or not like following.

protected void Page_Load(object sender, EventArgs e)
{
   PaymentType paymentType = PaymentType.CreditCard;
 
   if (paymentType.HasFlag(PaymentType.DebitCard))
   {
       Response.Write("Process Debit Card");
   }
   if (paymentType.HasFlag(PaymentType.CreditCard))
   {
       Response.Write("Process Credit Card");
   }
 
}

Now Let’s check out in browser as following. 

Image Loading

As expected it will print process Credit Card as we have assigned that value to enum. That’s it It’s so simple and cool.

Conclusion

In this tips we have learned how to check a enumration has definition for flag. this is method in C# 4.0 hopes help.Happy Programming.

Sign Up to vote for this article
Other popular Tips/Tricks
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top