How to enumerate an Enum in C# and VB.NET

To enumerate an Enum in C# and VB.NET you can use the snippet below.

Sample C#

public enum TestEnum
{
	These = 0,
	Are = 1,
	Sample = 2,
	Enums = 3,
	Duplicates = 3,
	Included = 4
}

static void Main(string[] args)
{
	foreach (var testEnum in Enum.GetNames(typeof(TestEnum)))
	{
		System.Console.WriteLine(testEnum);
	}
	Console.Read();
}

Sample VB.NET

Public Enum TestEnum
	These = 0
	Are = 1
	Sample = 2
	Enums = 3
	Duplicates = 3
	Included = 4
End Enum

Private Shared Sub Main(args As String())
	For Each testEnum As var In [Enum].GetNames(GetType(TestEnum))
		System.Console.WriteLine(testEnum)
	Next
	Console.Read()
End Sub

Please rate this snippet

How to convert a string to enum in Java

To convert a string to enum in Java you can use the following snippet.

Considering the following enum.

Sample Java

public enum Testenum {
  One,Two,Three,Four
}

you can cast an string to enum like this:

Sample Java

Testenum.valueOf("Two");

Please rate this snippet

How to get Enum by Descritption Attribute in C# and VB.NET

To get Enum by Descritption Attribute in C# and VB.NET you can use the following snippet.

Sample C#

public static T GetEnumFromDescriptionAttribute<T>(string description)
{
	var type = typeof(T);
	if (!type.IsEnum) throw new InvalidOperationException();
	foreach (var fieldInfo in type.GetFields())
	{
		var descriptionAttribute = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute)) as DescriptionAttribute;
		if (descriptionAttribute != null)
		{
			if (descriptionAttribute.Description != description) continue;
			return (T)fieldInfo.GetValue(null);
		}
		if (fieldInfo.Name != description) continue;
		return (T)fieldInfo.GetValue(null);
	}
	return default(T);
}

Sample VB.NET

Public Shared Function GetEnumFromDescriptionAttribute(Of T)(description As String) As T
	Dim type = GetType(T)
	If Not type.IsEnum Then
		Throw New InvalidOperationException()
	End If
	For Each fieldInfo As var In type.GetFields()
		Dim descriptionAttribute = TryCast(Attribute.GetCustomAttribute(fieldInfo, GetType(DescriptionAttribute)), DescriptionAttribute)
		If descriptionAttribute IsNot Nothing Then
			If descriptionAttribute.Description <> description Then
				Continue For
			End If
			Return DirectCast(fieldInfo.GetValue(Nothing), T)
		End If
		If fieldInfo.Name <> description Then
			Continue For
		End If
		Return DirectCast(fieldInfo.GetValue(Nothing), T)
	Next
	Return Nothing
End Function

Please rate this snippet