[Update] - posted this up on sadeveloper.net
When I started looking at the Visual Studio 2005 Beta, I listed a couple of toppings that I wanted to check out. Then I thought it might be a good idea write up a little “article” on each topic, for my own reference, and who knows, maybe for someone else's as well. So here goes the first one:
What it's all about
The idea is to split normal classes into several declarations, these declarations will typically reside in different files. During compilation, these declarations(partial classes) are combined into one and compiled as if there was only one class definition.
Examle
[Employee.cs]
public partial class Employee
{
string _name;
int _empNo;
public Employee(int empNo,string name)
{
_empNo = empNo;
_name = name;
}
}
[EmployeeProperties.cs]
public partial class Employee
{
public int EmpNo
{
get
{
return _empNo;
}
set
{
_empNo = value;
}
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
}
Rules
- All classes that will be joined together must be marked with the “partial” keyword. This will prevent someone from just adding a partial class to your existing class and messing around with the internal workings
- Of course members (fields,methods, properties etc.) can only be defined once throught all partial classes with the same name.
- All the partial definitions must be in the same namespace(also obvious) and must be contained in the same module(exe or dll).
- If you're planning to add partial classes in future, you can use the “partial” keyword, even though you only have one definition. There is no rule that states that you have to have at least 2 partial definitions to be able to use “partial” on a class.
Pro's
- Using partial classes we can devide one class into several files, allowing several developers to work on the same class at once while still having the full benefit of source control
- Allows you to split the functionality of your classes logically into groups. As in the example you can put all your properties in on file, constructors in another, business logic functions in another, or whatever suites your project best. This aids in avoiding “clutter“, as is demonstrated in the new ASP.NET code behind files.
Another good idea would be to put all the parts of your class that was generated by a code generator in one file.
Con's
- The major drawback I see in partial classes is that developers will use it to “extend” classes instead of normal OO mechanism, thus ending up with huge monolithic classes.
- The other issue is just around locating all the partial classes that contribute to a class. Hopefully Visual Studio or tools like ReShaper will be able to help us quickly navigate between partial classes instead of having to remember in which files they are defined. For now (an at all times really) you can just use a nice naming convention.