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.
Why use reflection if you know the interface ahead of time? Why not just test if it implements the interface then cast to that?
If you really must use reflection, get the properties on the interface type, so use this line to get properties: