views:

78

answers:

2

Given this definition:

[UniqueId("Ident")]
public class MyClass : MyBase
{
    public int Ident{ get; }
}

What is the best way from the "MyBase" class to get the "UniqueId" attribute, find the matching property name and get the underlying value?

+2  A: 

Wouldn't an abstract method / property in the base-class be more suitable?

public abstract int UniqueId {get;}

Via attributes, like so:

object GetUniqueId() // or int
{
    Type type = GetType();
    UniqueIdAttribute attrib = null;
    foreach(UniqueIdAttribute tmp in 
        type.GetCustomAttributes(typeof(UniqueIdAttribute), true))
    {
        attrib = tmp;
        break;
    }
    if (attrib == null) throw new InvalidOperationException();
    return type.GetProperty(attrib.PropertyName).GetValue(this, null);
    // perhaps cast here...         
}
Marc Gravell
no it would not.
Micah
Care to explain why? Anyway, I've updated my example to show via reflection
Marc Gravell
But I stress: reflection is best reserved for when there is no other route; I see no sensible reason why an abstract / virtual method isn't perfectly good here; it will be a lot quicker, too.
Marc Gravell
I would second the part about the abstract method/property (regardless of the unexplained response). Worst case, you could make it "public abstract object UniqueId" if "int" doesn't work.
patridge
or, indeed, protected if the outside world doesn't need to know about the details.
Marc Gravell
I rethought the scenario, and I took your advice and made it a virtual property.
Micah
Good choice. And thanks for revoking the down-vote (!)
Marc Gravell
A: 

I don't exactly understand why you'd want that attribute on the class. Wouldn't it be more obvious to add it to the property, like this:

public class MyClass
{
    [UniqueId]
    public int Ident{ get; }
}

You could access this value using something like

var identity = objectThatHasAnIdentity.GetId();

GetId could now be an extension method on object that implements a code similar to what Marc posted above

grootjans