Question

I have a question: Is there an elegant way of getting Attributes on a referenced field. Ie.:

public class C1: Base
{
    [MyAttribute]
    public string Field1;
}
public class Base
{
    private void Do(ref string field)
    {
          if (field has attributes)
              DoSomething();
    }
} 

How can I get attributes of a field in the method Do()?

Thanks in advance.

Was it helpful?

Solution

There's no way you can do that with ref string field signature. Attributes are applied to declarations (fields, classes, events etc.), not to "instances".

What you can do, is alter your method like this:

private void Do(Type fieldContainingType, string fieldName, ref string field)

and then use reflection to inspect fieldContainingType to see, what attributes are applied to field named fieldName. This approach, however, is extremely fragile and generally very bad.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top