String Enumeration

Hmanjarawala
Posted by Hmanjarawala under C# category on | Points: 40 | Views : 1175
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace SampleApp
{
class StringEnumerationAttribute : Attribute
{
public StringEnumerationAttribute(string value)
{
Value = value;
}

public string Value { get; set; }
}

static class StringEnum<E>
{
public static string Value(E e)
{
StringEnumerationAttribute[] attrib = typeof(E).GetField(e.ToString()).GetCustomAttributes(typeof(StringEnumerationAttribute), false) as StringEnumerationAttribute[];
if (attrib != null && attrib.Length > 0) return attrib[0].Value;
else return string.Empty;
}

public static E Parse(string value)
{
return (E)Enum.Parse(typeof(E), value);
}
}

enum WeekDays
{
[StringEnumeration(value: "Sunday")]
Sunday = 0,
[StringEnumeration(value: "Monday")]
Monday = 1,
[StringEnumeration(value: "Tuesday")]
Tuesday = 2,
[StringEnumeration(value: "Wednesday")]
Wednesday = 3,
[StringEnumeration(value: "Thursday")]
Thursday = 4,
[StringEnumeration(value: "Friday")]
Friday = 5,
[StringEnumeration(value: "Saturday")]
Saturday = 6
}


static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Form1());

WeekDays day = StringEnum<WeekDays>.Parse("Monday");
System.Diagnostics.Debug.WriteLine(StringEnum<WeekDays>.Value(day));
}
}
}

Comments or Responses

Login to post response