Find out if a property is declared virtual

Technically, properties are not virtual -- their accessors are. Try this:

typeof(Cat).GetProperty("Age").GetAccessors()[0].IsVirtual

If you wanted, you could use an extension method like the following to determine if a property is virtual:

public static bool? IsVirtual(this PropertyInfo self)
{
    if (self == null)
        throw new ArgumentNullException("self");

    bool? found = null;

    foreach (MethodInfo method in self.GetAccessors()) {
        if (found.HasValue) {
            if (found.Value != method.IsVirtual)
                return null;
        } else {
            found = method.IsVirtual;
        }
    }

    return found;
}

If it returns null, either the property has no accessors (which should never happen) or all of the property accessors do not have the same virtual status -- at least one is and one is not virtual.


You could use the IsVirtual property:

var isVirtual = typeof(Cat).GetProperty("Age").GetGetMethod().IsVirtual;

IsVirtual alone didn't work for me. It was telling me that all my non-virtual non-nullable properties were virtual. I had to use a combination of IsFinal and IsVirtual

Here's what I ended up with:

PropertyInfo[] nonVirtualProperties = myType.GetProperties().Where(x => x.GetAccessors()[0].IsFinal || !x.GetAccessors()[0].IsVirtual).ToArray();

PropertyInfo[] virtualProperties = myType.GetProperties().Where(x => !x.GetAccessors()[0].IsFinal && x.GetAccessors()[0].IsVirtual).ToArray();

Tags:

C#

Reflection