C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




convert an integer to an enum


Posted Date: 03 Jun 2008    Resource Type: Code Snippets    Category: C# Syntax

Posted By: Debasmit Samal       Member Level: Gold
Rating:     Points: 5



In the code sample, NumToEnum is a generic method that can convert an integer to any type of enum.

Function that will do all the work:


public T NumToEnum(int number)
{
return (T)Enum.ToObject(typeof(T), number);
}


This is a generic function that can convert a number to any type of enum.
Let's see example that makes use of this function. First, let's create some enums.


public enum DaysOfWeek
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}

public enum MonthsInYear
{
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
}


Now, see some code that uses NumToEnum.


int day = 3;
int month = 10;

//d is now DaysOfWeek.Thursday
DaysOfWeek d = NumToEnum(day);

//m is now MonthsInYear.November
MonthsInYear m = NumToEnum(month);




Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Number to enum  .  Integer to enum conversion  .  Integer to enum  .  Generic methods  .  Generic method  .  Converting integer to enum  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: creating notepad in VB.NET
Previous Resource: create a directory in C#.net
Return to Discussion Resource Index
Post New Resource
Category: C# Syntax


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

it support

Contact Us    Privacy Policy    Terms Of Use