Convert an enum to a List

Enum to List

Enum to List

An enum type internally contains an enumerator list. Whenever there is a situation that you have a number of constants that are logically related to each other, then it is the best way that you can group together these constants in an enumeration.


C# Syntax:
enum<name> { enumeration list; }

VB.Net Syntax:
Enum enumerationname[As datatype] memberlist End Enum
C# Enum to List

In most cases it is best to define an enum directly within a namespace so that all classes in the namespace can access it with equal convenience. In some situation we want to convert these enum values to List for programming convinence. The following program shows how to convert an enum to List in C# as well as VB.Net


C# Enum to List
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } enum Week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; private void button1_Click(object sender, EventArgs e) { List<Week> days = Enum.GetValues(typeof(Week)).Cast<Week>().ToList(); foreach (Week day in days) { MessageBox.Show(day.ToString()); } } } }
VB.Net Enum to List
VB.Net Enum to List
Public Class Form1 Enum Week Sunday Monday Tuesday Wednesday Thursday Friday Saturday End Enum Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim days As List(Of Week) = [Enum].GetValues(GetType(Week)).Cast(Of Week)().ToList() For Each day As Week In days MessageBox.Show(day.ToString()) Next End Sub End Class

Enum Basics

Enums are strongly typed constants which makes the code more readable and less prone to errors. It is useful when you have a set of values that are functionally significant and unchanged. More about.... Enum in C#

Enum Flags Attribute

The idea of Enum Flags is to take an enumeration variable and allow it hold multiple values. It should be used whenever the enum represents a collection of flags, rather than representing a single value. More about.... Enum Flags Explained



NEXT.....MemoryStream to file