Search code examples
c#.netgenericsreflection.net-4.0

Get static property of class from generic type parameter


Say I have the following:

public class GetById<TEntity> : where TEntity : Entity
{
    public Guid EntityId { get; set; }

    public TEntity Execute()
    {
        // Get the entity here
    }
}

What I would like to do is retrieve the value of a specific static property of the class that is passed in through TEntity. This property does not exist in the Entity base class, but it exists as a property of any of the different derived classes that will be passed in as the TEntity parameter. I've found similar questions on SO, but they all have the assumption that the property is declared in the base class as well.

Are there any ways of doing this through reflection or similar? This is a .NET 4.0 project.


Solution

  • The type system does not allow you to do this.

    You can use reflection:

    typeof(TEntity).GetProperty("MyProp", BindingFlags.Public | BindingFlags.Static)