# Wednesday, April 18, 2007
« c# HelloWorld from Ubuntu | Main | Comparing .NET 3.5 to 2.0 and 1.1 »
I came across a cross cutting infrastructure requirement today that would have been best solved by using AOP.  Since the application I was using already uses Spring.NET I immediately thought about implementing a method interceptor using Spring.NET's AOP facilities, I even found an interceptor already coded on the web that was exactly what I needed.  Of course there was one problem, .NET defaults all public methods to non-virtual and the class I was trying to apply AOP to was a wsdl.exe generated class with non-virtual methods.  This meant that Spring couldn't generate an AOP proxy at runtime for the method I wanted to add a pointcut to.  Argh!

I think defaulting every public member in .NET to virtual would have been a better decision than defaulting to non-virtual.  Java doesn't have a virtual keyword, every public method in Java is virtual by default.  Isn't that the whole point of OOP and inheritence?  At a whim, I should be able to subclass and override ANY public method.  Yeah, I may implement things incorrectly in my subclass, but the onus is on me.  Not marking methods virtual in .NET is basically saying you don't trust the next developer.  This is especially annoying since dynamic subclassing has become so common ala DynamicProxy.  Want to use NHibernate with lazy loading?  Well you can't unless you mark everything explitly virtual.  All this means to me is extra cutting and pasting; of course I'm going to make everything virtual.  My point is that virtual should be the default, it should be extra work to make it non-virtual - just like sealing a class.

Some of you may say, but virtual methods are slower than non virtual methods because of the method lookup.  True, virtual methods are slower, but...  And this is a big one, all method calls in c# are virtual method calls, regardless if they are marked virtual or not.  If I'm already paying the price of having virtual methods, then why can't we just treat them as such in code?!

Comments are closed.