Web developers wiki ASP.NET Sitecore Sharepoint Kentico by Evident Interactive



The code snippet below allows you to add a description to a C$ enum. The extensionmethod allows you to get the description in just one method call.

Example usage: C#:
public enum ExampleEnum
{
    [EnumDescription("This describes the first example")]
    FirstExample = 1,

[EnumDescription("This describes the second example")] SecondExample }

ExampleEnum example = ExampleEnum.FirstExample;

string text = example.Description();

// text is now "This describes the first example"

Include this code snippet in your project: C#:
namespace System
{
    public class EnumDescription : Attribute
    {
        public EnumDescription(string text)
        {
            Text = text;
        }

public string Text; }

public static partial class Extensions { public static string Description(this Enum enm) { Type type = enm.GetType(); MemberInfo[] memInfo = type.GetMember(enm.ToString()); if (memInfo != null && memInfo.Length > 0) { object[] attrs = memInfo[0].GetCustomAttributes(typeof(EnumDescription), false); if (attrs != null && attrs.Length > 0) { return ((EnumDescription)attrs[0]).Text; } } return enm.ToString(); } } }

 © Evident Interactive BV