When Is It Appropriate to Use C# Partial Classes

Why do we need partial Class in .NET

Partial classes provide a way to split the code of a class across files.

This way one file can contain generated code and another file could contain handwritten code. The generated code can than be regenerated without messing with the handwritten code. Had the custom code been added to the same file as the generated code, the regeneration would have overwritten it.

Visual Studio itself uses this in many places where designers generate code and users add logic. Sometimes Visual studio hides the generated code by only generating it during compilation (Compiling WPF applications generates a 'bridge' class between Xaml and 'code behind') and sometimes generated code is put in partial classes without providing an empty twin class which is left to the developer.

In general: when generating code use partial classes as a service to the developers that use the generator. And while we are at it: consider providing partial methods as well to allow the developer to hook in to the logic of the generated code so the developer is free to chose between implementing the partial method, sub classing the generated class for the correct reasons.

Best Practices: When not/to use partial classes

Partial classes are primarily for code-generator usage, such as designers - but I use the approach you have cited - in particular when an object implements multiple (non-trivial) interfaces, I find it useful to break it up 1 file per interface implementation. I also commonly have a file for the static methods, which are usually different enough from instance methods to warrant separation.

When should I use the Partial keyword?

Firstly, it seems that this is a way to bypass the lack of multiple inheritance in C# (aside from interfaces, of course). Are there any repercussions to doing so, aside from normal multiple inheritance issues, such as the Diamond Problem? Basically, just because I can, does it mean I should?

It doesn't do multiple inheritance. It's actually way more evil, since it exposes private variables -- but at the same time it doesn't introduce diamonds. Try the following code to see what I mean:

public class Test0
{
protected int bar;

public void Unexpected() { Console.WriteLine("3. {0}", bar); }
}

public partial class Test1
{
private int foo;

public void Foo() { Console.WriteLine("1. {0}", foo); bar = 1; }
}

public partial class Test1 : Test0
{
public void Bar() { Console.WriteLine("2. {0}", foo); foo = 1; }
}

class Driver
{
public static void Main()
{
var t1 = new Test1();
t1.Bar();
t1.Foo();
t1.Unexpected();
Console.ReadLine();
}
}

In other words, you should be very careful with variables.

Secondly, when exactly should I split up files? Just by reading this, it feels like I should be able to declare a nested class in its own file, and partial it together with the containing class, and thereby improve readability. Is this the point of Partial, or should it only be used as described in the above article?

Code generation is a well known example. I personally use partial classes a lot when dealing with the Facade pattern (which is very useful when creating WCF/SOAP services). In most cases I try to avoid it for the above reason.

What is the purpose of partial classes?

Partial classes allow code to not only add to the generated classes, but also implement optional functionality.

For example, there may be generated code which performs property validation (through IDataErrorInfo) but the validation on each property cannot be determined at generation time, the partial class allows the developer to specify the validation at a later point.

The generated file:

public partial class MyClass : IDataErrorInfo
{
partial void ValidateMyProperty(ref string error);

public string this[string propertyName]
{
get
{
string error = String.Empty;
if (propertyName == "MyProperty")
ValidateMyProperty(ref error);

return error;
}
}

public string Error { get { return String.Empty; } }

public int MyProperty { get; set; }
}

The developer implemented file:

public partial class MyClass
{
partial void ValidateMyProperty(ref string error)
{
if (MyProperty < 0)
error = "MyProperty cannot be negative.";
}
}

What are the benefits to using a partial class as opposed to an abstract one?

Partial classes have nothing to do with object inheritance. Partial classes are just a way of splitting the source code that defines a class into separate files (this is for example done when you create a new form in your Windows Forms application - one file is "your" code, another file .designer.cs contains the code that VS2008 manages for you).

Should you use a partial class across projects?

You can't write a partial class across projects. A partial class is a compile-time-only piece of syntactic sugar - the whole type ends up in a single assembly, i.e. one project.

(Your original DAL file would have to declare the class to be partial as well, by the way.)



Related Topics



Leave a reply



Submit