views:

146

answers:

2

I have the following attribute custom attribute, which can be applied on properties:

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class IdentifierAttribute : Attribute
    {
    }

For example:

    public class MyClass
    {
        [Identifier()]
        public string Name { get; set; }

        public int SomeNumber { get; set; }
        public string SomeOtherProperty { get; set; }
    }

There will also be other classes, to which the Identifier attribute could be added to properties of different type:

    public class MyOtherClass
    {
        public string Name { get; set; }

        [Identifier()]
        public int SomeNumber { get; set; }

        public string SomeOtherProperty { get; set; }
    }

I then need to be able to get this information in my consuming class. For example:

    public class TestClass<T>
    {
        public void GetIDForPassedInObject(T obj)
        {
            var type = obj.GetType();
            //type.GetCustomAttributes(true)???
        }
    }

What's the best way of going about this? I need to get the type of the [Identifier()] field (int, string, etc...) and the actual value, obviously based on the type...

+3  A: 

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;
    }  
Richard Friend
thanks - can't use "prop" within the lambda in FirstOrDefault, but i've sorted it :-)
alex
Ahh yes, was writing it in notepad ;-) fixed.
Richard Friend
I've marked my property with [Identifier()] but the .GetProperties() returns all other properties EXCEPT this one?! my attribute seems to hide it??
alex
Try specifying the binding flags such as GetProperties(BindingFlags.Public | BindingFlags.Instance);
Richard Friend
+1  A: 
public class TestClass<T>
{
    public void GetIDForPassedInObject(T obj)
    {
        PropertyInfo[] properties =
            obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);            

        PropertyInfo IdProperty = (from PropertyInfo property in properties
                           where property.GetCustomAttributes(typeof(Identifier), true).Length > 0
                           select property).First();

         if(null == IdProperty)
             throw new ArgumentException("obj does not have Identifier.");

         Object propValue = IdProperty.GetValue(entity, null)
    }
}
this. __curious_geek