By using Partial keyword we can partly devides our class,Struct, Interface into two or more files. Later when the application gets compiled all the files gets combined.
Splitting application code into several files is helpful,
For windows application, we have one Form1.cs file and another one is Form1.Designer.cs and if you check code behind of these files, you can see partial class defined there. In Form1.Designer.cs, we have definition of all controls that we add in our form and Form1.cs file contains all the events, custom code of our application. When these files gets compiled, they gets combined into one class.
Like we declare classes, Structs, Interfaces partial, we can declare partial methods as well. following are the conditions while declaring partial methods.
See below sample code where class partialClass splits in two parts with partial keyword and also defined partial method ShowMessage in one part and implemented in second part.
Splitting application code into several files is helpful,
- When there is a large project development, we can devide our class into several different files so that it enables multiple programmers to work simultaneously on that class.
For windows application, we have one Form1.cs file and another one is Form1.Designer.cs and if you check code behind of these files, you can see partial class defined there. In Form1.Designer.cs, we have definition of all controls that we add in our form and Form1.cs file contains all the events, custom code of our application. When these files gets compiled, they gets combined into one class.
Like we declare classes, Structs, Interfaces partial, we can declare partial methods as well. following are the conditions while declaring partial methods.
- We can declare partial methods in partial type (Class,Struct) only.
- partial method signature is defined in one part of partial type and implementation in other part of partial type.
- Return type of partial method should be void.
- We can't use access modifier on partial methods. They are private by default.
See below sample code where class partialClass splits in two parts with partial keyword and also defined partial method ShowMessage in one part and implemented in second part.
+
Code
using System; namespace partial_class_and_methods { //partial class part1 partial class partialClass { partial void ShowMessage(string message); } //partial class part2 partial class partialClass { partial void ShowMessage(string message) { Console.WriteLine("Partial method declaration with message" + message ); } } }
1 comment :
Good explaination...!!!
Post a Comment