Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using reflection to get properties of class inheriting an interface

I have the following scenario where I would like to get the properties of a class which implements an interface, however excluding those properties which are virtual. Just to make things clear I am going to give you a small example:-

Imagine we have the following Interface:-

public interface IUser
{
    int UserID { get; set; }
    string FirstName { get; set; }
}

A class which 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. When the class does not 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 won't get excluded) like the below:

var entityProperties = typeof(User).GetProperties();

Someone has got any idea please? I searched however I was not able to find any results. Thanks in advance for your help.

like image 798
krafo Avatar asked Feb 11 '23 19:02

krafo


1 Answers

I suspect you want IsFinal:

To determine if a method is overridable, it is not sufficient to check that IsVirtual is true. For a method to be overridable, IsVirtual must be true and IsFinal must be false. For example, a method might be non-virtual, but it implements an interface method.

So:

var entityProperties = typeof(User).GetProperties()
                                   .Where(p => p.GetMethod.IsFinal);

Or possibly:

var entityProperties = typeof(User).GetProperties()
                                   .Where(p => !p.GetMethod.IsVirtual ||
                                               p.GetMethod.IsFinal);
like image 185
Jon Skeet Avatar answered Feb 14 '23 12:02

Jon Skeet