Westbrook
Westbrook

Reputation: 21

Custom Attributes for fields

I did a custom attribute for fields that receives a string. Then I'm using the custom attribute in an enum. I need to get the result of "MyMethod" from FieldAttribute, but It doesn't return the string,

Here's what I have:

Enum and attribute:

public enum CustomEnum
{
    [Field("first field")]
    Field1,
    [Field("second field")]
    Field2,
    [Field("third field")]
    Field3
}

[AttributeUsage(AttributeTargets.Field)]
public class FieldAttribute : Attribute
{
    private string name;

    public FieldAttribute(string name)
    {
        this.name = name;
    }

    public string LastName { get; set; }

    public string MyMethod()
    {
        return this.name + this.LastName;
    }
}

Usage:

public class Program
{
    public static void Main(string[] args)
    {
        PrintInfo(typeof(CustomEnum));
    }

    public static void PrintInfo(Type t)
    {
        Console.WriteLine($"Information for {t}");
        Attribute[] attrs = Attribute.GetCustomAttributes(t);

        foreach (Attribute attr in attrs)
        {
            if (attr is FieldAttribute)
            {
                FieldAttribute a = (FieldAttribute)attr;
                Console.WriteLine($"   {a.MyMethod()}");
            }
        }
    }
}

Some help please!!!

Upvotes: 2

Views: 261

Answers (1)

Vlad
Vlad

Reputation: 35584

It works like this:

public static void PrintInfo(Type t)
{
    Console.WriteLine($"Information for {t}");

    var pairs =
        from name in t.GetEnumNames()
        let member = t.GetMember(name).Single()
        let attr = (FieldAttribute)member.GetCustomAttributes(typeof(FieldAttribute), false)
                      .SingleOrDefault()
        let text = attr.MyMethod()
        select (name, text);

    foreach (var (name, text) in pairs)
        Console.WriteLine($"{name} -> {text}");
}

Explanation: you are using GetCustomAttributes on the type, but you need actually the enum constants which are indeed fields on the enum type. So you need to get the MemberInfo for the enum constant and ask for its attribute.


For a really old compiler you can use a simple

public static void PrintInfo(Type t)
{
    Console.WriteLine($"Information for {t}");

    foreach (string name in t.GetEnumNames())
    {
        MemberInfo member = t.GetMember(name).Single();
        FieldAttribute attr =
            (FieldAttribute)member.GetCustomAttributes(typeof(FieldAttribute), false)
                      .SingleOrDefault();
        string text = attr.MyMethod();
        Console.WriteLine(name + " -> " + text);
    }
}

Upvotes: 2

Related Questions