Using Visual Studio Form Designer With Forms Extending Abstract Classes

For a recent project I wanted to create an abstract form base class. This way some global functionality can be inherited by all of my forms and interface methods can be defined.

But the result was this error message as soon as I tried to open one of my derived from classes in the Visual Studio form designer:

The designer must create an instance of type <type name>, but it can't because the type is declared as abstract.

Hereupon I’ve searched for a solution in the web and it seems that I was not the only one that had the idea to derive some form classes from an abstract base class. To solve the problem I’ve created a dummy implementation of my abstract base class and derived the form classes from this dummy implementation. This way the form classes can be displayed in the Visual Studio form designer again.

In C# the classes look like this then:

public abstract partial class BaseForm : Form
{
  // Methods of your abstract class...
}

#if DEBUG
public class BaseFormImpl : BaseForm
{
  // The dummy implementation of the abstract BaseForm class.
}
#endif

#if DEBUG
public partial class RealForm : BaseFormImpl
#else
public partial class RealForm : BaseForm
#endif
{
  // One of the forms extending the base form.
}

And for VB .NET developers it looks like this:

Public MustInherit Partial Class BaseForm
  Inherits Form
  ' Methods of the abstract base class...
End Class

#if DEBUG
Public Class BaseFormImpl
  Inherits BaseForm
  ' The dummy implementation of the abstract BaseForm class.
End Class
#endif

Public Partial Class RealForm
#if DEBUG
  Inherits BaseFormImpl
#else
  Inherits BaseForm
#endif
  ' One of the forms extending the base form.
End Class

Probably you have noticed the compiler directives: obviously that’s not necessary that the forms work correctly inside the form designer again. But I don’t like to have unnecessary code inside the released product (and the dummy implementation of the abstract BaseForm class is really useless). Therefore I used these conditional compiler directives to make sure that this dummy class is only used in debug mode.

Did you come across this issue yourself already, too?

This post is also available in Deutsch.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>