2

I'm trying to get a list of properties in a class where the property is marked with the decorator [Ignore] (SQLite.Net), although I believe the question is applicable for any decorator.

var ignored = typeof(T)
            .GetType()
            .GetProperties().Where(p =>
                p.GetCustomAttributes<SQLite.Net.Attributes.IgnoreAttribute>())
            .ToList();

I've tried various combinations of this - the one here doesn't even compile, but accessing the p.CustomAttributes collection does; however, it doesn't return the correct property. For completeness, here is the property in T:

private ProductCategory _category;

[Ignore]
public ProductCategory Category
{
    get { return _category; }
    set
...

Please could someone point me in the right direction here - are CustomAttributes even the right place to be looking for this?

1 Answer 1

7

Your code sample has two major problems -

Firstly, typeof(T) returns a type, so you don't need to call GetType() on it (doing so returns information about the Type class, rather than the returning information about "T").

The second problem is that you can't just call "p.GetCustomAttributes(whatever)" in the Where lambda because that doesn't result in a boolean result, you need to call "p.GetCustomAttributes(whatever).Any()".

Your code also didn't compile on my computer due to the generic type param in the GetCustomAttributes call.. but I'm sure I've done that in the past! Maybe I'm using a different version of the framework or something.

The code that did work for me is as follows:

var ignored = typeof(T)
    .GetProperties()
    .Where(p => p.GetCustomAttributes(typeof(IgnoreAttribute), inherit: true).Any())
    .ToList();

(Whether or not you need "inherit: true" depends upon your object model but I suspect that it's appropriate in the majority of cases).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.