C# Partial Types
C# provides a concept to write source code in separate files and compile it as a single unit. This feature is called partial types and included in C# 2.0. The partial keyword is used to create partial types.
It allows us to write partial class, interface, struct and method in two or more separate source files. All parts are combined when the application is compiled.
Let's see an example. Here, we are creating a partial class that includes a depositeAmount() function in the Customer.cs file and a withdraw() function in the Customer2.cs file. Both functions are stored in separate file and combined when compiled.
C# Partial Class Example
// Customer2.cs
Output:
Current balance is: 2000
amount is deposited
Available balance is: 3000
500 is withdrawn
Available balance is: 2500Partial classes provide a way to split the code of a class across files.
This way one file can contain generated code and another file could contain handwritten code. The generated code can than be regenerated without messing with the handwritten code. Had the custom code been added to the same file as the generated code, the regeneration would have overwritten it.
Visual Studio itself uses this in many places where designers generate code and users add logic. Sometimes Visual studio hides the generated code by only generating it during compilation (Compiling WPF applications generates a 'bridge' class between Xaml and 'code behind') and sometimes generated code is put in partial classes without providing an empty twin class which is left to the developer.
In general: when generating code use partial classes as a service to the developers that use the generator. And while we are at it: consider providing partial methods as well to allow the developer to hook in to the logic of the generated code so the developer is free to choose between implementing the partial method or sub classing the generated class for the correct reasons.
Database fist approach will generate model classes which are by default partial.
Comments
Post a Comment