views:

118

answers:

4

When does it become a good idea to have your class separate into two .cs and have it as a partial class?

Are there some signs showing that it is time to go with partial class?

Thanks!

+13  A: 

When you have to autogenerate a portion of those classes and manually write the rest of the content of the classes.

This is so that you can put the machine-generated content in one file and hand-coded code in another file. The advantage of doing so is that when you have to regenerate the source code, your hand-coded portion won't get wiped out.

This is how MS generates class content for its GUI designers ( think of those *.designer.cs file), and allows you to put the meat of your logic in other related file ( *.cs)

Ngu Soon Hui
+4  A: 

If you have auto-generated code you want to extend, a partial class is a great way to do that.

For example, extending LINQ to SQL classes that get generated.

Dan
+1  A: 

Lets say you have event handlers and other GUI code in one place, and want to keep other non GUI related code in one place. The MVC pattern which is not easy in C#.

Priyank Bolia
Why not have GUI code in one *class* and non-GUI code in another *class*?
Martinho Fernandes
You are living in ideal world, most of the C# code have Business logic written within the event handlers itself. At least having partial classes and extracting provide some sort of better code management, also this type of refactoring can be done easily in VS
Priyank Bolia
+2  A: 

Like the others said, auto-generated code is a good reason. I also use partial class sometimes when I want to put a nested class in its own file.

public partial class MyClass
{
    private class NestedClass
    {
        ...
    }
}

Plus there is this little trick to nest a file in the solution explorer (to do like winform and nest the Form1.designer.cs file).

<Compile Include="Foo.1.cs">
  <DependentUpon>Foo.cs</DependentUpon>
</Compile>

Nesting file in Visual Studio

SelflessCoder