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 :)

0 comments:

Post a Comment