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
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.