Shachaf.Gortler
Shachaf.Gortler

Reputation: 5745

Check fields attributes using reflection

I'm trying to find a fields in a class has a Obsolete attribute ,

What I have done is , but even thought the type has an obselete attribute its not found during iteration :

public bool Check(Type type)
{
    FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic |  BindingFlags.Instance);

  foreach (var field in fields)
  { 
     if (field.GetCustomAttribute(typeof(ObsoleteAttribute), false) != null)
     {
        return true
     }
  }
}

EDIT :

class MyWorkflow: : WorkflowActivity
{
 [Obsolete("obselset")]
 public string ConnectionString { get; set; }
}

and using it like this , Check(typeof(MyWorkflow))

Upvotes: 1

Views: 222

Answers (1)

tchelidze
tchelidze

Reputation: 8318

Problem is that ConnectionString is nor Field and nor NonPublic.

You should correct BindingFlags and also, use GetProperties method to search for properties.

Try the following

public static bool Check(Type type)
{
  var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
  return props.Any(p => p.GetCustomAttribute(typeof(ObsoleteAttribute), false) != null);
}

Upvotes: 4

Related Questions