Tuesday, May 18, 2010

Partial Classes

The concept of the partial class came into play in Framework 2.0.  However, I've noticed that people have either forgotten or didn't notice this handy keyword.

Framework 1.0

If you used the 1.0 Frameworks you noticed when you created UI elements that all the back-end code for those controls ended up going into the form's code behind.  Typically, this resided in a region called something like "Designer Generated Code".

To me at least, this cluttered your code behind with code that was required but not it wasn't YOUR code.

Framwork 2.0

The solution to this and many other problems came in the 2.0 release of the Framework with this new keyword; partial. 

A partial class essentially is a keyword that tells the compiler "hey, my class is defined across several definitions; usually across multiple files".  It almost reminds of me header files in C++, but that's neither here nor there.

You can use partial on a class, struct, or interface.

So what?

Well, the two reasons MSDN's documentation suggests using the partial keyword are the same two reasons I like it.

1. It keeps system generated code in its own section away from your code.
2. (This is the big one...) Allows teams of developers to break a class into several logical files to reduce/prevent waiting on your code to be checked in to edit a section.

Like I said, reason 2 is my favorite.  Countless times I've needed to add an item to an enum, add an overload of a function to a class... and its checked out.  I would even say in about 90% of the cases, the other developer was changing things unrelated to what I wanted to change!

My rule of thumb is to break the code into logical chunks when using a partial class.  For example, if I had an ATM object then I might break each class into the functions the ATM can perform.  Obviously, the class name will be the same but I like to use a classname_function type name for all the partial files.

Example:

ATM.cs (maybe where I keep the constructor, declarations, and properties)
ATM_Withdraw.cs
ATM_Deposit.cs
ATM_GetStamps.cs
ATM_PrintStatement.cs

Usage

Using the partial keyword is easy!  Simply put "partial" after the scope (public, private, protected,etc) and before the type (class, interface, enum).

Example:

public partial class Form1 : Form

Note:  This would be the main declaration of the class.  A subsequent declaration wouldn't need the inherits.  So your other partials would like like this:  public partial class Form1

Other Considerations

Keep in mind that the entire class definition has to be in the SAME namespace.

All parts must have the same scope (accessibility).  IE, its public or private, etc not mix and match.

No comments:

Post a Comment