Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only properties that implement an interface

Tags:

c#

reflection

I have an class that implements an interface. I'd like to examine only the property values that implement my interface.

So, let's say for example I have this interface:

public interface IFooBar {
    string foo { get; set; }
    string bar { get; set; }
}

And this class:

public class MyClass :IFooBar {
    public string foo { get; set; }
    public string bar { get; set; }
    public int MyOtherPropery1 { get; set; }
    public string MyOtherProperty2 { get; set; }
}

So, I need to accomplish this, without the magic strings:

var myClassInstance = new MyClass();
foreach (var pi in myClassInstance.GetType().GetProperties()) {
    if(pi.Name == "MyOtherPropery1" || pi.Name == "MyOtherPropery2") {
        continue; //Not interested in these property values
    }
    //We do work here with the values we want. 

}

How can I replace this:

if(pi.Name == 'MyOtherPropery1' || pi.Name == 'MyOtherPropery2') 

Instead of checking to see if my property name is == to a magic string, I'd like to simply check to see if the property is implemented from my interface.

like image 371
Jeff Reddy Avatar asked Nov 15 '11 21:11

Jeff Reddy


2 Answers

Why use reflection if you know the interface ahead of time? Why not just test if it implements the interface then cast to that?

var myClassInstance = new MyClass();
var interfaceImplementation = myClassInstance as IFooBar

if(interfaceImplementation != null)
{
    //implements interface
    interfaceImplementation.foo ...
}

If you really must use reflection, get the properties on the interface type, so use this line to get properties:

foreach (var pi in typeof(IFooBar).GetProperties()) {
like image 194
Paul Tyng Avatar answered Nov 09 '22 14:11

Paul Tyng


I tend to agree that it looks like you want to cast to the interface, as Paul T. suggests.

The information you are asking about, however, is available in the InterfaceMapping type, available from the GetInterfaceMap method of the Type instance. From

http://msdn.microsoft.com/en-us/library/4fdhse6f(v=VS.100).aspx

"The interface map denotes how an interface is mapped into the actual methods on a class that implements that interface."

for example:

var map = typeof(int).GetInterfaceMap(typeof(IComparable<int>));
like image 26
phoog Avatar answered Nov 09 '22 16:11

phoog