.NET (296) administrative (41) Ajax (42) AngularJS (2) ASP.NET (144) bicycle (2) books (180) browser (8) C# (134) cars (1) chess (28) CodePlex (10) Coma (8) database (47) deployment (3) Entity Framework (2) essay (112) flash/shockwave (2) flex (1) food (3) friend (2) game (20) idea (5) IIS (8) javascript (82) LInQ (2) Linux (6) management (4) manga (42) misc (672) mobile (1) movies (91) MsAccess (1) murder (2) music (64) mysql (1) news (100) permanent (1) personal (68) PHP (1) physics (2) picture (307) places (12) politics (13) programming (504) rant (120) religion (3) science (43) Sharepoint (3) software (58) space (1) T4 (2) technology (11) Test Driven Development (4) translation (2) VB (2) video (97) Visual Studio (44) web design (46) Windows API (8) Windows Forms (3) Windows Server (5) WPF/Silverlight (63) XML (11)

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.

No comments: