ASP.NET Hosting

C# feature request for Anders

Hello Anders,

Could you add to C# support for things like this?

enum Colors {Red, Green, Blue};
string[Colors] htmlColors = new string[] {"#FF000", "#00FF00", "#0000FF"};

This is something we have in Delphi (you remember Delphi, don't you?) that I miss in C#. I don't think it would be difficult to add to the compiler. But if we don't have it yet, maybe there is a problem somewhere?

Of course, we can find more examples where this syntax would help, and not only with strings.
If we go a bit further, we can even imagine something like this:

enum Colors<string> {Red = "#FF0000", Green = "#00FF00", Blue = "#0000FF"};

Let me know what you think,
Yours truly,
Fabrice

3 Comments

  • So you have an associative array (dictionary) where the keys are of type 'Color' and the values are of type 'string'?.



    You could do that with Generics, I guess...!?

  • This is getting close, but the advantage with enums is that the set of possible keys is well defined and compile-time cheched.

  • What I do for this is use a custom attribute that I call &quot;MemberDescriptionAttribute&quot;. Then I can get it from reflection.



    [AttributeUsage(AttributeTargets.All)]

    public class MemberDescriptionAttribute : Attribute

    {

    public readonly string Description;



    public MemberDescriptionAttribute(string description)

    {

    this.Description = description;

    }



    public static string FromMember(object obj)

    {

    return((MemberDescriptionAttribute)obj.GetType().GetMember(

    obj.ToString())[0].GetCustomAttributes(typeof(MemberDescriptionAttribute), false)[0]).Description;

    }



    public static string FromType(object obj)

    {

    return((MemberDescriptionAttribute)obj.GetType().GetCustomAttributes(typeof(MemberDescriptionAttribute), false)[0]).Description;

    }



    public static ArrayList ToArrayList(System.Type type)

    {

    string[] names = Enum.GetNames(type);

    ArrayList toReturn = new ArrayList( names.Length );

    DictionaryEntry de;

    foreach(string n in names)

    {

    object current = Enum.Parse(type, n, true);

    string description = MemberDescriptionAttribute.FromMember(current);

    de = new DictionaryEntry();

    de.Key = description;

    de.Value = n;

    toReturn.Add( de );

    }



    return toReturn;

    }

    }



    class Class1

    {

    public enum Colors

    {

    [MemberDescription(&quot;#FF000&quot;)]

    Red,



    [MemberDescription(&quot;#00FF00&quot;)]

    Green,



    [MemberDescription(&quot;#0000FF&quot;)]

    Blue

    }



    [STAThread]

    static void Main(string[] args)

    {

    ArrayList list = MemberDescriptionAttribute.ToArrayList(typeof(Colors));



    foreach(DictionaryEntry de in list)

    {

    Console.WriteLine(de.Value + &quot; = &quot; + de.Key);

    }



    Console.ReadLine();

    }

    }

Comments have been disabled for this content.