4

I have these attributes for this class, and I am wondering how to access them from within the class. ServedClassName is a custom attribute, and that is the one I am actually trying to access.

[Guid("24889af6-e174-460b-ab52-7fb5a925926e")]
[ServedClassName("ASCOM ProxyClient Telescope")]
[ProgId("ASCOM.DeviceProxyClient.Telescope")]
[ClassInterface(ClassInterfaceType.None)]
public class Telescope : ReferenceCountedObjectBase, ITelescopeV3

To access the ProgID, I use this: Marshal.GenerateProgIdForType(this.GetType());

2

1 Answer 1

6
object [] attrs = GetType().GetCustomAttributes(typeof(ServedClassNameAttribute), true);

will give you a list of the custom attributes of type ServedClassNameAttribute on your class. You can then walk through the attribute instances like this:

foreach (ServedClassNameAttribute attr in attrs)
{
    // Do something with attr
}
Sign up to request clarification or add additional context in comments.

3 Comments

Wouldn't I use (typeof(...),false)? Visual studio is saying that it doesn't have an overload for just type. Or should I put true there?
My bad, I'll fix the answer. You want to use inherit=true if you are deriving from a class that also may have your attribute set on its type. If you only care about whether the current class has the attribute set and not its base class, use inherit=false.
If you just use GetCustomAttributes(bool) (msdn.microsoft.com/en-us/library/kff8s254.aspx), you return all attributes for the current Type instance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.