Partial Classes

Earlier in this chapter, you saw that the abstraction pattern can be useful in catering to platform differences while still getting a lot of code reuse. However, in cases where most of a class can be shared across platforms and you simply want to provide some extensions for specific platforms, abstraction can sometimes become cumbersome. In these scenarios, C#’s support for partial classes can be very useful. Partial classes allow you to split the definition of a class across multiple files. These files will be merged at compile time and treated as though they were in the same file.

Partial classes are commonly found in platforms that make use of generated source code, such as ASP.NET Web Forms and Windows Forms. By using partial classes, the developer can work in an entirely separate file from the generated code, avoiding any collision between them but still providing a single class implementation to the compiler. This approach is also used by MonoTouch’s view controller designer files and Mono for Android’s resource classes.

The usefulness of partial classes is not limited to cases involving generated code. When combined with file linking, partial classes allow you to share the common source across each platform, but then also augment that with platform-specific extensions as needed. Since the different files are seen as one logical file in the eyes of the compiler, each part has full access to anything defined in the others, including private variables and methods. ...

Get Mobile Development with C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.