Partial class, interface and structure was introduced in C# 2.0. Now it is possible to split the definition of an class, interface and structure over more than one source files. Moreover the other parts of the class, struct, or interface should be defined in the same namespace or assembly. All the parts must have the partial keyword and same access modifier like as public, private, and so on. For more about partial method refer the article Partial Methods in C Sharp with example.
Why Partial Class, Interface or Struct?
- Allow more than one developers to work simultaneously on the same class, struct or interface.
- Partial class are particularly helpful for customizing auto generated code by the IDE. Whenever the IDE generate the code then tool may define some partial class, interface, methods and further customization of partial class, interface is done by the developers without messing with the system generated code.
Key Points about Partial Class, Interface or Struct
- During code compilation, all the parts should be available to form the final class, interface or struct.
- Any member declared in the one part will be available to all other parts.
- If any part has Inheritance, then it applies to the entire class.
- Different parts of a class or struct may inherit from different interfaces.
- If any part is declared abstract, then the whole class, interface or struct is considered abstract.
- If any part is declared sealed, then the whole whole class, interface or struct is considered sealed.
Auto-Generated Partial Class in Asp.Net by IDE
When ever you add an Asp.Net web from or web page to your web application or website than visual studio automatically added a partial class to your's page code behind. This code behind class is Inherited by the ASPX page.
- public partial class Default : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- // your's code
- }
- }
Partial Class, Interface or Struct Example
- class MyNamespace
- {
- partial class Example
- {
- void Test() { //write your code }
- }
- partial class Example
- {
- void Test2() { //write your code }
- }
- }
- partial interface IExample
- {
- void ITest();
- }
- partial interface IExample
- {
- void ITest2();
- }
- partial struct SExample
- {
- void STest()
- {
- //write your code
- }
- }
- partial struct SExample
- {
- void STest2()
- {
- //write your code
- }
- }
Note
- The partial modifier is not available for delegate or enum.
What do you think?
I hope you will enjoy this tricks while programming C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.
No comments:
Post a Comment