Partial class is a concept where a single class can be split into 2 or more files. This feature is useful when a class consists of a large number of members (functions, properties and so on).
In such cases functions can be developed in one file and properties in another.
Advantages:
- It avoids programming confusion (in other words better readability).
- Multiple programmers can work with the same class using different files.
- Even though multiple files are used to develop the class all such files should have a common class name.
Note:
- When compilation is done all the files will be compiled into a single file.
- When the CLR executes the program it doesn't differentiate between a normal class or partial class.
Foldername : Console
Filename: partial1.cs
- using System;
- partial class A
- {
- public void Add(int x,int y)
- {
- Console.WriteLine("sum is {0}",(x+y));
- }
- }
Filename: partial2.cs
- using System;
- partial class A
- {
- public void Substract(int x,int y)
- {
- Console.WriteLine("Difference is {0}", (x-y));
- }
- }
-
- class Demo
- {
- public static void Main()
- {
- A obj=new A();
- obj.Add(7,3);
- obj.Substract(15,12);
- }
- }
Note
When the program is compiled, the .exe file will be created based on the file name in which the main function exists.
Figure 1: Folder and File names location
The following is the procedure for compiling a partial class:
Note: Microsoft also uses partial classes for every program.
For example, create a window application and you will find the following screens.
Code behind file
Designer file
Thank you.