PeteH
PeteH

Reputation: 2454

Accessing instance-level custom attributes in c#

Imagine I have the following code:

class A
{
    [UsefulAttribute("foo")]
    B var1;
    [UsefulAttribute("bar")]
    B var2;

    ...
}


class B
{
    public string WriteSomethingUseful()
    {
        ?????
    }
}  

My question is, what code do it need to put in the ????? such that, when I call var1.WriteSomethingUseful I get an output of foo, and when I call var2.WriteSomethingUseful I get an output of bar?

I've got a feeling this is quite a straightforward question, I think my main issue is that I have worked myself into a state of confusion by thinking about it for too long!!!

Seriously, I have defined UsefulAttribute and realise that part of the code must be a GetCustomAttributes(typeof(UsefulAttribute)...) call. Where I'm getting confused is how to pull these values out on the actual instance, rather than at the type level.

Many thanks, Pete

Upvotes: 3

Views: 1517

Answers (2)

BrokenGlass
BrokenGlass

Reputation: 160992

Since your WriteSomethingUseful() method is within the type B, but your attributes are declared within type A you will not be able to access them based on an instance - you simply don't have a reference to A.

The current B instance might not be related to A at all, and without being able to retrieve "the type of the class instance (if any) that contains the current B instance" - which is not possible in C# - there is no general way to do this.

Upvotes: 3

Chris Shain
Chris Shain

Reputation: 51369

This isn't possible. For starters, what if multiple different instances of A have references to the same B? Or what if the same instance of B is referenced by both var1 and var2?

When you set the attribute on the field, you are attaching that attribute to the type of class A, not the instance of class B stored in the field var1.

The normal way to go about this is to store the data as a property of B, set it either via a property setter or a constructor parameter, and then access the property from the WriteSomethingUseful method.

Upvotes: 6

Related Questions