Custom attribute on property – Getting type and value of attributed property

Something like the following,, this will use only the first property it comes accross that has the attribute, of course you could place it on more than one..

    public object GetIDForPassedInObject(T obj)
    {
        var prop = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                   .FirstOrDefault(p => p.GetCustomAttributes(typeof(IdentifierAttribute), false).Count() ==1);
        object ret = prop !=null ?  prop.GetValue(obj, null) : null;

        return ret;
    }  

Leave a Comment