Stewart Alan
Stewart Alan

Reputation: 1643

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.

Upvotes: 9

Views: 2198

Answers (1)

LukeHennerley
LukeHennerley

Reputation: 6434

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));

Upvotes: 11

Related Questions