1

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 Answers 2

2

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... } 
Sign up to request clarification or add additional context in comments.

5 Comments

Care to explain why? Anyway, I've updated my example to show via reflection
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.
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.
or, indeed, protected if the outside world doesn't need to know about the details.
I rethought the scenario, and I took your advice and made it a virtual property.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.