views:

46

answers:

2

While moving some code around for investigation purposes, I came across a little feature of .NET that I was unaware of, which is that the form class must be the first class in a form module for the form designer to work. The following stops the designer from working:

public class myClass
{
}

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

...
}

It still compiles (with a warning) and runs, but it wont design. If I move myClass to the bottom of the file then it works fine. Does anyone know why this is the case?

Also, this implies that there's a set of rules to code layout within a form that I am unaware of. Is there a list of these somewhere that anyone knows of - or have I found the only one?

A: 

Apparently that's just the designer. It's nothing to worry about.

This has nothing to do with C# itself, but more with the Visual Studio designer to find and draw the form on the screen.

Snake
+3  A: 

I think this is an artifact of the .NET 1.1 designer. Back then there was no partial keyword yet, the designer had the unenviable task to find back the InitializeComponent() method, even in code that was in the middle of being edited. No help from the compiler.

To avoid the risk of completely interpreting code incorrectly, it had some basic rules about what that code should look like. And requiring the form class to be the first class in the file makes a lot of sense. If that rule wouldn't be there, it would have to be able to parse through a class that might have very basic syntax errors, like unbalanced braces. Simply declaring "cannot load form" in that case wouldn't make anybody happy.

This requirement couldn't be lifted once the partial keyword became available, it still has to support forms that were designed in earlier versions.

It is the only code layout rule I know. There are lots of other possible mishaps, tinkering with InitializeComponent() by hand is always a good way to get the WSOD.

Hans Passant