Continuing my efforts to educate my team on the new features of 2.0, here’s what I had to say about Partial Types. (Maybe I don’t “get” partial types…they seem more like they would be sources of confusion than actually useful…)
One of the first things you will likely notice, when you go to create a new form (win or web) is that the “code behind” is different. Incomplete. Or, put in the manner of the Talking Heads:
And you may find yourself, creating a new WinForm;
And you may find yourself, looking in the Code-Behind
And you may find definitions, in another part of the project
And you may say to yourself, “This is not my beautiful class, this is not my beautiful form”
And you may ask yourself, “Where is that call to InitializeComponent();?”
And you may ask yourself, “My God, what have they done?”
Ok, that sucked. But you’re looking at a partial class. The most obvious example of it is that your InitializeComponent and “Windows Forms Designer Generated Code Region” go away when you hit F7 to view code. For some this is good I guess, but for me, annoying. For one, I like to wire up my events in InitializeComponent() rather than in the designer. For two, InitializeComponent() is how I learned how controls and forms and pages work in .Net. Because in ASP.Net especially, it was a leaky abstraction, and often your button events would get unwired and you had to go find the right place to do it. But I digress.
Partial Types. Very simply you separate parts of a class into other files. That’s all it is. You will see:
public
partial class Form1 : Form
or
public
partial class MyType
And then in the other class, another partial class Form1 declaration. That’s it. All there is to it. The compiler puts them together as one unit, and the IDE reads them as one unit (not in solution explorer – the files remain separate). So, if you have two different files for the Form1 class, you would still see all of the objects and methods and properties and fields available in each file from Intellisense, the class explorer, the members drop down, and all that other stuff as you would were they in the same file.
I’m not really sure what the huge benefit of this is. Some say that a large class file could be broken down to multiple files to make it more manageable. I say that a class that is so big that having it in one file is unwieldy is a #1 target for a refactor. Others say that it is good for source control, so you could have one developer working on one part of the class, and another in another area, and they wouldn’t be concurrently editing the same file. I say get a source control system that supports simultaneous checkout and merge checkin. So I don’t know.
I personally won’t be using this feature much outside of the ones that the IDE does on its own, but it’s important to know what the partial type thing is, and how it works, so that you don’t freak out the first time you can’t find your InitializeComponent(); It’s still there, just not.
Tags:
.Net Code