Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what conditions it is good to have a "partial class?"

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!

like image 522
pencilCake Avatar asked Dec 02 '09 14:12

pencilCake


People also ask

What is the benefit of partial classes?

Purpose of partial classes is to allow a class's definition to span across multiple files. This can allow better maintainability and separation of your code.

What are all true about a partial class?

A partial class is a class whose definition is present in 2 or more files. Each source file contains a section of the class, and all parts are combined when the application is compiled.

What is the use of partial classes in C Plus Plus?

A partial class is a construct that supports scenarios in which you are modifying one part of a class definition, and automatic code-generating software—for example, the XAML designer—is also modifying code in the same class. By using a partial class, you can prevent the designer from overwriting your code.

Can partial class be inherited?

Inheritance cannot be applied to partial classes.


3 Answers

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)

like image 195
Graviton Avatar answered Sep 16 '22 17:09

Graviton


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

like image 42
Jeff Cyr Avatar answered Sep 16 '22 17:09

Jeff Cyr


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.

like image 24
Dan Avatar answered Sep 19 '22 17:09

Dan