November 2005 - Posts

Extension Methods: Still Not Multiple Inheritance

Extension Methods can be used as a piece of pseudo-multiple-inheritance for methods, but they really have a different purpose than Inheritance and Multiple Inheritance. In some cases, Extension Methods can be used as a substitute for Multiple Inheritance. That said, if C# 5.0 (presently fictitious) has both Extension Methods and Multiple Inheritance, both will continue to be used as solutions for different types of problems.

Inheritance gives us the 'is a kind of' relationship between classes. It also causes us to inherently gain functionality (methods & events), attributes (properties & fields), and state (values in properties & fields). It also allows us to cast back up the class hierarchy, tie together many related members in a tight manner, and override functionality thus giving us polymorphism. When desiring to make changes that impact all classes further down the hierarchy, we must have access and/or liberty to make changes to the base class - a luxury that is not always afforded us.

Extension Methods do not give us any kind of relationship ('is a kind of', 'contract for functionality', or otherwise). They do not give us attributes nor do they give us state. They do not give us casting, they do not tie together many related members, nor do they allow overriding & polymorphism. Extension Methods, however, do not require any modifications to the base classes and thus we can extend functionality of an existing class without restriction.

What Extension Methods do is give us the ability to add a simple, stand alone method to existing classes with no intrusion whatsoever. I've heard them described (quite accurately) as "syntactic sugar" implemented in the compiler. It merely changes:

   MyStaticIListHelperClass.Merge(IList1, IList2);

into:

   IList1.Merge(IList2);

My understanding of Extension Methods is that the latter statement in this example would actually compiles into the former.

While Extension Methods can serve a small part of the same function as Multiple Inheritance, they certainly don't eliminate the need for Multiple Inheritance and they are really intended for a different purpose. Nevertheless, they are a most welcome addition and will be of great use in many of our solutions. All we have to do now is wait for Visual Studio Next.

Happy Coding
- Shaun

with 1 Comments