Post

Inheritance vs. Partial

Someone at a presentation I presented at recently asked, “Instead of inheriting from a base control (TextBox), couldn’t you just create a partial class and add the additional functionality?”

It’s an interesting idea; however, there are several problems associated with the idea… some technical, others not so technical. The two biggest reasons are:

  1. In my experience, you aren’t really able to hijack the System namespace. By this I mean you aren’t able to write the following code:
1
2
3
4
5
6
Namespace System.Windows.Forms
 Public Class SomeNewWidget
   Inherits System.Windows.Forms.Control

 End Class
End Namespace

At this point, just about everywhere in your project would now have the squiggly underlines since you’ve essentially just hijacked the System namespace and all sub-namespaces. In addition, the only thing in the System namespace tree would be System.Windows.Forms.SomeNewWidget… nothing else, noda, that’s it.

Now, there might be some way to try to pull this off using various attributes (don’t know if there is or not), but this leads into the next problem.

  1. How the heck do you maintain such a project? If you change the basic behavior of some control (or even worse, multiple controls), how are you, as the developer, supposed to keep track of such changes. Is what you are using in this project a System.Windows.Forms.TextBox or a modified TextBox? Let’s say you could do the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Namespace System.Windows.Forms
  Partial Class TextBox

    Public Property MirrorText() As String
      Get
        Return Me.Text
      End Get
      Set(ByVal value As String)
        Me.Text = value
      End Set
    End Property

  End Class
End Namespace

And then you have another developer that “knows what they are doing” come along and inherits from System.Windows.Forms.TextBox to create a new control based on TextBox. What type of complications are they going to encounter because of this partial class? Imagine trying to track down potential bugs? What if you encounter what you think to be a bug in a TextBox, report it to Microsoft and they ask for a sample. (Bear in mind that the above code is somewhat behaved, but imagine if you really change the behavior of whatever control in question.) You create a sample project to reproduce the problem only to find that in the sample project that the problem doesn’t exist. Again, what are you next steps to track down the problem? How would you even begin to search for the offending code?

In the end, Partial Classes are not really designed to mimic inheritance (by extending some existing object), that’s what inheritance is for. Partial Classes are designed to allow you to create “new” classes that can have a physical separating between generated code and hand written code. The fact that you could use (or rather abuse) this for other purposes doesn’t change what their intention was for.

This post is licensed under CC BY 4.0 by the author.