9

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.

Community
  • 1
  • 1
Stewart Alan
  • 1,521
  • 5
  • 23
  • 45

1 Answers1

11

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));
LukeHennerley
  • 6,344
  • 1
  • 32
  • 50
  • 1
    This is assuming that the implementing property name matches the name of the property on the interface, which isn't necessarily the case. – Jon Egerton Mar 15 '13 at 14:40
  • @JonEgerton so it would be possible for `A` in `Foo` to be `C`, for example? – LukeHennerley Mar 15 '13 at 14:41
  • 1
    That's defo possible in VB.Net, not sure about C#. Might not be an issue if the OP can assume he's not working with VB.Net assemblies. – Jon Egerton Mar 15 '13 at 14:45
  • @JonEgerton If not, I can't understand how they can be different? You can't have `public string C {get; set;}` and that handles the `IFoo.A` implementation. I can't understand what you mean :) – LukeHennerley Mar 15 '13 at 14:45
  • 1
    @JonEgerton Seeing as the tag is `C#` I can't see how that is possible. I understand if this was `VB.Net` because you would have `Public Property C As String Implements IFoo.A`. That is not valid in C# as far as I am aware. – LukeHennerley Mar 15 '13 at 14:47
  • 1
    In VB you can have `Public Property C As String Implements IFoo.A` Not sure if the same can be done with C#'s syntax. Its actually useful where you implement interfaces with the same property names. – Jon Egerton Mar 15 '13 at 14:47
  • Thanks, that does exactly what I need it to. – Stewart Alan Mar 15 '13 at 15:32