I was reading the MSDN article on the Partial keyword, and this part caught my eye:
The partial keyword indicates that other parts of the class, struct,
or interface can be defined in the namespace. All the parts must use
the partial keyword. All the parts must be available at compile time
to form the final type. All the parts must have the same
accessibility, such as public, private, and so on.[…]
All the parts that specify a base class must agree, but parts that
omit a base class still inherit the base type. Parts can specify
different base interfaces, and the final type implements all the
interfaces listed by all the partial declarations. Any class, struct,
or interface members declared in a partial definition are available to
all the other parts. The final type is the combination of all the
parts at compile time.
I had two questions regarding this concept:
-
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?
-
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?
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:
In other words, you should be very careful with variables.
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.