In general I am against making properties virtual altogether. The problem
with virtual properties is that both the getter and setter are virtual. Virtual
properties can not be inlined by the compiler (today at any rate). Therefore,
for a simple point of extensibility, you have negatively impacted the performance
every time a property value is retrieved. If a property can be inlined then
it is effectively a field when it comes to performance.
I believe the better approach is to leave all properties nonvirtual. If you
want to provide an extensibility point to property setting (get is rare) then either
introduce a protected property that is virtual or use a virtual method to allow
derived classes to set the property value. Here is an example of either approach.
//Option 1
class MyClass
{
public string Name
{
get { return m_strName; }
set { SetName(value); }
}
protected virtual void SetName ( string value )
{ ... }
}
//Option 2
class MyClass
{
public string Name
{
get { return m_strName; }
set { NameCore = value; }
}
protected virtual string NameCore
{
get { return m_strName; }
set { m_strName = value; }
}
}
An important point. If you truly need to provide an extensibility point for
setting AND getting a property value then making the property virtual is reasonable.
However this is, in my experience, rare. There is no real benefit in calling
a virtual method from a property getter/setter so don't try working around the problem
that way either. Notice that in the sample above for option 2 the non-virtual
and virtual getters both did the same thing. If the non-virtual getter had
called the virtual getter then we would have accomplished nothing.