Search code examples
c#coding-stylepartial-classes

Best Practices: When not/to use partial classes


I have been using the partial class modifier for some time in order to put helper classes in their own file.

Today we got a new guy and he said that the last team he worked with didn't allow partial classes for this because modifying a helper class that is in a separate file would cause the main partial class file to get out of whack with the changes. Also, they were only allowed to put a helper classes inside of the main class as the last resort so that everything remained decoupled.

What do you think? Is there any problem using partial classes like this or does it boil down to preference?

For instance, I usually have something like this:

  • MainClass.cs
  • MainClass.Helper1.cs
  • MainClass.Helper2.cs

...

// Inside of MainClass.cs I have code like this:

public abstract partial class MainClass
{
    // ...
}

// Then in the MainClass.Helper1.cs I have:

partial class MainClass
{
   private class Helper1
   {
       // ...
   }
}

Solution

  • 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.