title: BindingFlags.DeclaredOnly alternative to avoid ambiguous properties of derived classes (AmbiguousMatchException)
body: <p>I'am looking for a solution to access 'flatten' (lowest) properties values of a class and its derived via reflection by property names.</p>
  
  <p>ie access either <em>Property1</em> or <em>Property2</em> from the <em>ClassB</em> or <em>ClassC</em> type :</p>
  
  <pre><code>   public class ClassA
      {
          public virtual object Property1 { get; set; }
  
          public object Property2 { get; set; }
      }
      public class ClassB : ClassA
      {
          public override object Property1 { get; set; }
      }
      public class ClassC : ClassB
      {
      }
  </code></pre>
  
  <p>Using simple reflection works until you have virtual properties that are overrired (ie <em>Property1</em> from <em>ClassB</em>). Then you get a <em>AmbiguousMatchException</em> because the searcher don't know if you want the property of the main class or the derived.</p>
  
  <p>Using BindingFlags.DeclaredOnly avoid the AmbiguousMatchException but unoverrided virtual properties or derived classes properties are ommited (ie <em>Property2</em> from <em>ClassB</em>).</p>
  
  <p>Is there an alternative to this poor workaround : </p>
  
  <pre><code>// Get the main class property with the specified propertyName
  PropertyInfo propertyInfo = _type.GetProperty(propertyName, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
  
      // If not found, get the property wherever it is
      if (propertyInfo == null)
              propertyInfo = _type.GetProperty(propertyName);
  </code></pre>
  
  <p>Furthermore, this workaround not resolve the reflection of 2nd level properties : getting <em>Property1</em> from <em>ClassC</em> and <em>AmbiguousMatchException</em>  is back.</p>
  
  <p>My thoughts : I have no choice except loop... Erk... ??</p>
  
  <p>I'am open to Emit, Lambda (is the Expression.Call can handle this?) even DLR solution.</p>
  
  <p>Thanks !</p>