In previous versions of Visual Studio classes are confined to a single file. It was not possible to split up a single class into multiple files. In order to split up a class we have to use the keyword “Partial”. The purpose of the Partial Class is to allow more than one programmer to write code for the same class, at the same time.
Example
In the above example, the Employee class is split into 2 parts. The first part defines the GetName() method, and the second part defines the GetAge() method. When you compile this program both parts will be combined and compiled.
The important point to remember is both sections use the keyword Partial and the public access modifier.
Points to considered on creating Partial Class
- All the parts must use the partial keyword.
- During compile time, all the parts should be available to form the final class.
- All the parts should have the same access modifiers. – Public, Private, Protected and etc.,
- Any member declared in the partial class is available to all other parts.
- If any part is abstract, the entire class is abstract
- If any part is sealed, then entire class is sealed.
- If any part has Inheritance, then it applies to the entire class.
- We can create the Partial Structs, Interfaces and methods in the same way as we create partial classes.
- Different parts of the partial calls can inherit from different interfaces.
In the above example two parts are declared as public. In the following example we will create one part as abstract.
If you create an object for the Employee class, you will get the following error: “Cannot create an instance of the abstract class or interface Examples.Employee”. This is because the second part is declared as abstract, so the whole class became abstract. Hence you cannot create an object. We can create nested classes as partial class; even when the main class is not partial.Output
Important Points in Partial Method
No comments:
Post a Comment