2

Given the following class

[KeyField("dap_name")]
public class nhs_acquisition_profile
    : DALObject
    , IDisposable
{
    public nhs_acquisition_profile()
        : base()
    {
    }

    public nhs_acquisition_profile(String ConnectionString)
        : base(ConnectionString)
    {

    }


}

How could I find the value of the KeyField Attribute but from the base class.

2
  • 1
    this.GetType() is probably your friend, if I understand your scenario correctly. If not, it could do with some sample code to better illustrate your problem. Commented Sep 25, 2017 at 16:06
  • 1
    You can use relection on the DALObject type to find its inheritors and then get the custom attributes on those - but you'll still need to know which one you're looking for, though - so that might not be what you're after if for some reason you need to do this via the base type. Commented Sep 25, 2017 at 16:07

1 Answer 1

4

I suppose you need it in a construction phase

public DALObject() // base constructor
{
    var fieldAttr = GetType() // real type
        .GetCustomAttributes(typeof(KeyFieldAttribute), true) // look for attribute
        .FirstOrDefault(); // can take more than one, it's an example
    var resultField = (fieldAttr as KeyFieldAttribute)?.Field; // cast and use
}

The same code will works the same in other functions in the class

Sign up to request clarification or add additional context in comments.

Comments

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.