Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write enum with # character?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace NumberedMusicScores
{
    public enum KeySignatures
    {
        C,
        G,
        D,
        A,
        E,
        B,
        FCress,
        CCress,
        F,
        Bb,
        Eb,
        Ab,
        Db,
        Gb,
        Cb
    }
}

I want FCress and CCress shown as F# and C# if I use it. How to achieve this?

I tried this : How to use ? character in an enum , but the Description in [Description("F#")] seems doesn't exist. (Underlined by red line, and it even doesn't shows anything to "Resolve" if I right-clicked it.

Update : Clarifications :

  1. It's not a duplicate. Since duplicate answer is not an enum, but a class which configured as an enum. I want enum solution.
  2. If it doesn't possible, then please answer "it's not possible", rather than marking it as duplicate.
  3. I already read them before I made this post.

Thank you.

like image 832
Moses Aprico Avatar asked Dec 21 '25 01:12

Moses Aprico


1 Answers

The PCL framework won't allow the Description attribute. You could just create a simplified version of the attribute.

public class MyDescription : Attribute
{        
    public string Description = { get; private set; }

    public MyDescription(string description)
    {
       Description = description;
    }
}

Then using Thomas' answer from this thread, do this:

public static string GetDescription(this Enum value)
{
    Type type = value.GetType();
    string name = Enum.GetName(type, value);
    if (name != null)
    {
        FieldInfo field = type.GetField(name);
        if (field != null)
        {
            MyDescription attr = 
                   Attribute.GetCustomAttribute(field, 
                     typeof(MyDescription)) as MyDescription;
            if (attr != null)
            {
                return attr.Description;
            }
        }
    }
    return null;
}

For your enum:

public enum KeySignatures
{
    //...
    [MyDescription("F#")]
    FCress,
    [MyDescription("C#")]
    CCress,
    //...
}
like image 104
keyboardP Avatar answered Dec 22 '25 21:12

keyboardP