Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it appropriate to use C# partial classes?

I was wondering if someone could give me an overview of why I would use them and what advantage I would gain in the process.

like image 616
Asterix Avatar asked Aug 30 '10 15:08

Asterix


People also ask

What should C be used for?

C is a powerful general-purpose programming language. It can be used to develop software like operating systems, databases, compilers, and so on.

Is there any reason to use C?

It was mainly developed as a system programming language to write operating system. The main features of C language include low-level access to memory, simple set of keywords, and clean style, these features make C language suitable for system programming like operating system or compiler development.

When would you choose to use C rather than C++?

C has a stable ABI (Application Binary Interface) increasing compatibility between different compilers. 8. C is somewhat more efficient than C++ since it doesn't need for Virtual Method Table (VMT) lookups. VMT — It is a mechanism used in programming languages to support dynamic dispatch (or Runtime Method Binding).


2 Answers

The biggest use of partial classes is to make life easier for code generators / designers. Partial classes allow the generator to simply emit the code they need to emit and they do not have to deal with user edits to the file. Users are likewise free to annotate the class with new members by having a second partial class. This provides a very clean framework for separation of concerns.

A better way to look at it is to see how designers functioned before partial classes. The WinForms designer would spit out all of the code inside of a region with strongly worded comments about not modifying the code. It had to insert all sorts of heuristics to find the generated code for later processing. Now it can simply open the designer.cs file and have a high degree of confidence that it contains only code relevant to the designer.

like image 73
JaredPar Avatar answered Oct 19 '22 19:10

JaredPar


Another use is to split the implementation of different interfaces, e.g:

partial class MyClass : IF3 {     // main implementation of MyClass }   partial class MyClass : IF1 {     // implementation of IF1 }  partial class MyClass : IF2 {     // implementation of IF2 } 
like image 20
relascope Avatar answered Oct 19 '22 18:10

relascope