Thursday, May 03, 2007

C# partial classes and file naming conventions

I find that partial classes in C# have more uses than just the automatic .Designer.cs created by numerous designers in your IDE of choice.

In certain scenarios, I will create partial classes and use multiple files.  I consider the [Class Name].cs as the primary file and [Class Name].[Name].cs as the satellite files.  The name is up to you, but should succinctly indicate the function and preferrably is one word.

I've found in practice it has worked very well, with regards to maintenance and reducing the time to understand a class.  I've been using this convention for a while, and felt it was time to review, given a few ideas I've been tossing around.

Currently I only use it for classes that are large enough to warrant separating out functional areas.  Additionally, if the class implements a complex interface or a related set of interfaces I may move these to a separate file.

I consider this is appropriate for larger classes and therefore you would always start off with a single file and as your implementation grows, reconsider if it is worth separating.

  • Limiting the public interface of the class to the primary file, so it is very easy for a developer to view the file and determine the public API
    • Move protected and private members to a separate file
      • [Class Name].private.cs
    • When a class has a significant number of private and protected members, separate as
      • [Class Name].private.cs
      • [Class Name].protected.cs

I know regions can provide similar functionality, assuming your editor supports outlining, but I tend to see them either overused or not at all.  When viewing a file in [insert simple text viewer of your choice], regions provide little value.

I usually limit regions to:

#region private fields
#region constructors
#region public members
#region protected members
#region private members

Thoughts?