Thursday, January 07, 2010

Tricky behaviour in .NET when inheriting methods

A friend of mine showed me a little information from MSDN that described the behaviour of methods that have the same name as other methods from the base class. Go to the MSDN site and scroll to the Override and Method Selection section.

A small excerpt: Override methods are not considered as declared on a class, they are new implementations of a method declared on a base class. Only if the C# compiler cannot match the method call to an original method on Derived will it try to match the call to an overridden method with the same name and compatible parameters.

Long story short: if you create a method in a derived class that has the same name as a method in the base class, the method in the derived class will always be used, even if the base class method matches better the call signature. In other words Derived.DoWork(double value) will be used instead of Base.DoWork(int value), even the value passed is an integer. Indeed, the double value method will be used even if there is a Derived.DoWork(int value) method, but one that overrides a method in Base.

You can solve this by casting to the base class, but the best idea is to never create methods with identical names to ones in the base class.