Tuesday, November 29, 2011

[.NET] Enum converter

Working with Enum will make your code become meaningful. This is some tips for you to control Enum and convert it between other types. Follow code:


1:  using System;  
2:  namespace EnumConverter  
3:  {  
4:    public enum Numbers  
5:    {  
6:      One = 1,  
7:      Two = 2,  
8:      Three = 3,  
9:      Four = 4,  
10:      Five = 5  
11:    }  
12:    internal class Program  
13:    {  
14:      private static void Main()  
15:      {  
16:        Console.WriteLine(" - From Enum to String is {0}", Numbers.One);  
17:        Console.WriteLine(" - From Enum to Int is {0}", (int)Numbers.One);  
18:        Console.WriteLine(" - From String of Enum to Enum is {0}", (Numbers)Enum.Parse(typeof(Numbers), "Two"));  
19:        Console.WriteLine(" - From Int of Enum to String of Enum is {0}", Enum.GetName(typeof(Numbers), 3));  
20:        Console.WriteLine(" - From Int of Enum to Enum is {0}", (Numbers)4);  
21:        Console.WriteLine(" - From String of Enum to Int of Enum is {0}", (int)Enum.Parse(typeof(Numbers), "Five"));  
22:        Console.WriteLine(" - Type of Enum is {0}", typeof(Numbers));  
23:        Console.ReadKey(true);  
24:      }  
25:    }  
26:  }  

No comments:

Post a Comment