← Back to home

Partial classes

Ted is all excited about the upcoming partial classes (the ability to have a class implementation spread over several source files) in the CLR.  He writes:

As part of the C# 2.0 release, Microsoft/ISO are introducing an interesting new feature as part of the language; it’s not as sexy as something like generics, perhaps, but I think it stands to serve as a far more powerful and important feature in the long run: partial classes.

More specifically, he is worried about accidental overriding:

I can accidentally introduce, through overriding, errors into the code because I don’t follow invariants assumed by the code-generator.

I fail to see how partial classes help mitigate this problem since nothing prevents both you and the code generator to create methods with the same name and signature in different files.

There is benefit to partial classes, though, but Ted seems to miss it.  The problem with the way code generation is typically performed nowadays in Java is with inheritance: 

  1. You extend a generated class or
  2. A generated class extends yours.

The problem with solution 1) is that it makes it impossible for your class to extend another class, since Java and C# only support single inheritance of implementation.  Partial classes can come in handy in such a case.

This feature is interesting but it also opens the door for the resurrection of long-forgotten linker problems, since a compilation phase is no longer guaranteed to produce a valid class…  It will be interesting to see how Microsoft handles this problem.

Comments (6)

Rafael Alvarez

So, basically they made delelegation a first class citizen in the language... interesting...

Ryan Campbell

From the horse's mouth: "Upon compilation, the C# compiler gathers all definitions of a partial type and combines them. The resulting IL generated by the compiler shows a single combined class, rather than several constituent classes." http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/vbconcprogramminglanguagefuturefeatures.asp Since the partial types are resolved at compile time, the compiler will prevent duplicate method signatures. You won't have any linker problems because there is no linker.

Howard M. Lewis Ship

Sounds like they've implemented Objective-C categories for C#.

Techie McNameDropper

Looks to me like MS have [insert probably misguided analogy that I believe makes me look clever and knowledgable here].

Frank Bolander

Isn't this just a fancy way of doing an #include ... directive(a la C/C++) for inner classes. PseudoCode version: class MyClass { #include PartialClass1; #include PartialClass2; } MFC/ATL rears it's ugly head again.

Fritz Schenk

Why not base the class system in prototypes like javascript?. It can still be compiled. An extending is easy.