Sunday, July 18, 2010

Determining if a Property is declared virtual via Reflection

Today I was trying to determine if a property is declared virtual via Reflection but I could not find a "IsVirtual" property in the PropertyInfo class.

The solution is quite simple - a property itself is not virtual but the accessor methods have the desired "IsVirtual" property defined. This code snippet demonstrates how to determine if a property is declared virtual:

var stringType = typeof(string);
var props = stringType.GetProperties();

foreach (var prop in props)
{
  foreach (var accessor in prop.GetAccessors())
  {
    Console.WriteLine("Property {0} accessor {1} declared as virtual {2}", prop.Name, accessor.Name, accessor.IsVirtual);
  }
}

I cannot imagine a situation in c# where I can declare a property that has a virtual set method but a non virtual get method or vice versa!

If you can point me to a situation where I'm able to do this in c# I would highly appreciate that :)

1 comment:

  1. Hello,

    let's say you have this interface:

    public interface ITest {
    string MyTest { get; set; }
    }

    Now you have this class :

    public class MyClass: ITest {
    public string MyTest { get; set; }
    }

    I think that your method will say that MyTest is virtual because it comes from the interface. But if you inherit from MyClass, you won't be able to redefine MyTest, so it is not virtual. I think that in order to complete your method, you should also check if accessor.IsFinal is false.

    ReplyDelete