Search code examples
c#attributesfilehelpers

Getting values from Custom Field Attributes in C#


This morning I embarked on what I thought would be a quick exercise to use custom field attributes. Having tried many things and searching many examples (most involving class rather than field attributes), I'm officially stuck.

My code is below. One peculiarity is that the class is built in FileHelpers using the classbuilder. My various partially successful attempts did manage to get the fieldnames from this class though, so I believe that part works fine.

What I want to do (per the comment in the code) is a) Run through the fields, b) for each, see if the DBDataTypeAttribute Attribute exists, and c) The seemingly hardest part - getting the values from the attribute (FieldType string, and AllowNulls bool).

Any comments appreciated!

Mark

class Program
{
    static void Main(string[] args)
    {
        // Desired output:
        System.Type userType = null;
        userType = ClassBuilder.ClassFromString(@"
                                                public class ExpenseReport
                                                {
                                                    [FieldQuoted('""', QuoteMode.OptionalForRead, MultilineMode.AllowForRead)]
                                                    [DBDataTypeAttribute(FieldType = ""varchar(1000)"", AllowNulls = true)]
                                                    public String UniqueID;
                                                    [FieldQuoted('""', QuoteMode.OptionalForRead, MultilineMode.AllowForRead)]
                                                    public String ERNum;
                                                }");

        object[] attributes;
        attributes = userType.GetCustomAttributes(typeof(DBDataTypeAttribute), true);
        foreach (Object attribute in attributes)
        {
            // Would like to be able to ID for each field whether the DBDataTypeAttribute is present, and get the FieldType and AllowNulls Values

            DBDataTypeAttribute a = (DBDataTypeAttribute)attribute;
            Console.WriteLine("Attribute: ", a.FieldType);
            Console.ReadLine();

        }
    }
}

[AttributeUsage(AttributeTargets.Field)]
public class DBDataTypeAttribute : System.Attribute
{
    private string fieldtype;
    public string FieldType
    {
        get { return fieldtype; }
    }

    private string allownulls;
    public string AllowNulls
    {
        get { return allownulls; }
    }

}

Solution

  • Pretty simple; you have to get them from the fields, not the type.

    foreach( FieldInfo field in userType.GetFields() )
    {
        DBDataTypeAttribute attribute = (DBDataTypeAttribute)Attribute.GetCustomAttribute(field, typeof(DBDataTypeAttribute));
        if( attribute != null )
        {
            // Do something with it.
        }
    }