Archive

Posts Tagged ‘enum’

Quick Tip: Converting an Enum from a string using C# Generics

August 3rd, 2009 No comments

Here’s a quick tip for you. Converting a string back to an Enum using Generics in C#.

private static T ToEnum<T>(string value)
{
	return (T) Enum.Parse(typeof(T), value);
}

Nice and easy, here’s an example usage – very lame I know.

// Original enum
UriFormat uriFormat = UriFormat.SafeUnescaped;
// Persisted value
string uriFormatText = uriFormat.ToString();
// Back to the enum from the persisted value
UriFormat uriFormatParsed = ToEnum<UriFormat>(uriFormatText);

Console.WriteLine(uriFormat);
Console.WriteLine(uriFormatText);
Console.WriteLine(uriFormatParsed);

Another juicy tidbit is coming, hang in there.

{lang: 'en-GB'}
Share

Quick Tip: Iterate through an enum in .NET

April 19th, 2009 3 comments

Here’s a quicky for you. Iterating through an Enum in .NET, replace ‘IconResource‘ with the Enum you want to iterate.

C#

Array enumValues = System.Enum.GetValues(typeof(IconResource));

foreach (IconResource resource in enumValues)
{
	Console.WriteLine("Resource: {0}", resource);
}

VB.NET

Dim enumValues As Array = System.[Enum].GetValues(GetType(IconResource))

For Each resource As IconResource In enumValues
    Console.WriteLine("Resource: {0}", resource)
Next

Useful?

{lang: 'en-GB'}
Share