Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Reflection to get all properties of an object not implemented by an interface

I want to be able use reflection to loop through the properties of an object that DO NOT implement an interface

Essentially I want to achieve the opposite of this How do I use reflection to get properties explicitly implementing an interface?

The reason is I want to map objects to another object where any properties that are not defined by an interface are added instead to a List of KeyValuePairs.

like image 748
Stewart Alan Avatar asked Mar 15 '13 14:03

Stewart Alan


1 Answers

Using this example:

interface IFoo
{
  string A { get; set; }
}
class Foo : IFoo
{
  public string A { get; set; }
  public string B { get; set; }
}

Then using this code, I get only PropertyInfo for B.

  var fooProps = typeof(Foo).GetProperties();
  var implementedProps = typeof(Foo).GetInterfaces().SelectMany(i => i.GetProperties());
  var onlyInFoo = fooProps.Select(prop => prop.Name).Except(implementedProps.Select(prop => prop.Name)).ToArray();
  var fooPropsFiltered = fooProps.Where(x => onlyInFoo.Contains(x.Name));
like image 188
LukeHennerley Avatar answered Nov 13 '22 23:11

LukeHennerley