C# – How to check if a property is virtual with reflection

creflectionvirtual

Given an object, how can I tell if that object has virtual properties?

var entity = repository.GetByID(entityId);

I tried looking in:

PropertyInfo[] properties = entity.GetType().GetProperties();

But couldn't discern if any of the properties would indicate virtual.

Best Answer

PropertyInfo[] properties = entity.GetType().GetProperties()
    .Where(p => p.GetMethod.IsVirtual).ToArray();

Or, for .NET 4 and below:

PropertyInfo[] properties = entity.GetType().GetProperties()
    .Where(p => p.GetGetMethod().IsVirtual).ToArray();

That will get a list of public virtual properties.

It won't work for write-only properties. If it needs to, you can check CanRead and CanWrite manually, and read the appropriate method.

For example:

PropertyInfo[] properties = entity.GetType().GetProperties()
    .Where(p => (p.CanRead ? p.GetMethod : p.SetMethod).IsVirtual).ToArray();

You could also just grab the first accessor:

PropertyInfo[] properties = entity.GetType().GetProperties()
    .Where(p => p.GetAccessors()[0].IsVirtual).ToArray();