Using reflection to get properties of a class that inherits an interface
I have the following scenario in which I would like to get the properties of a class that implements an interface, but excluding those properties that are virtual. To be clear, I will give you a small example: -
Imagine we have the following interface: -
public interface IUser
{
int UserID { get; set; }
string FirstName { get; set; }
}
Class that implements this interface: -
public class User: IUser
{
public int UserID { get; set; }
public string FirstName { get; set; }
public virtual int GUID { get; set; }
}
Now what I would like to do is get the properties of the class excluding the virtual one. When the class doesn't implement the interface, the following works just fine: -
var entityProperties = typeof(User).GetProperties()
.Where(p => p.GetMethod.IsVirtual == false);
However, when the interface is implemented, the above line of code will not return any results. If I remove the "where" it works fine (however the virtual property is not excluded) as shown below:
var entityProperties = typeof(User).GetProperties();
Anyone have an idea please? However, I searched but couldn't find any results. Thanks in advance for your help.
source to share
I suspect you want IsFinal
:
To determine if a method is overridden, it is not enough to check that IsVirtual is true. For a method to be overridden, IsVirtual must be true and IsFinal must be false. For example, a method might not be virtual, but it implements an interface method.
So:
var entityProperties = typeof(User).GetProperties()
.Where(p => p.GetMethod.IsFinal);
Or perhaps:
var entityProperties = typeof(User).GetProperties()
.Where(p => !p.GetMethod.IsVirtual ||
p.GetMethod.IsFinal);
source to share