Paul S Chapman
Paul S Chapman

Reputation: 832

C# Given a custom class and custom attribute how can you find the attributes of a class from the base class

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.

Upvotes: 2

Views: 222

Answers (1)

ASpirin
ASpirin

Reputation: 3651

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

Upvotes: 4

Related Questions