Powered by Blogger.

Saturday, March 1, 2014

Partial class in C#.Net:



In this article we will discuss about partial class in C#.Net. What is the advantage of using partial  class and how to implement partial class.

Also check out:

- Bind dropdownlist using arraylist or hashtable in C#.Net

- Delete file in C#.Net

- Working with enterprise library for data access in asp.net Part-3

We can split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the
application is compiled.

Advantages:
This is very much helpful while working with large projects, where multiple developers can work in the same class file.

When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.

We have to use keyword partial to implement partial class.

public partial class MyClass
{
    public void MyMethod1()
    {
    }
}

public partial class MyClass
{
    public void MyMethod2()
    {
    }
}

Similarly we can define partial interface too like below:

partial interface IMyInterface
{
    void myMethod1();
}

partial interface IMyInterface
{
    void myMethod2();
}

Some points to remember while working with partial class, interface or structure.
- All partial-type definitions meant to be parts of the same type must be modified with partial.
- The partial modifier can only appear immediately before the keywords class, struct, or interface.
- Nested partial types are allowed in partial-type definitions.
- All partial-type definitions meant to be parts of the same type must be defined in the same  assembly and the same module (.exe or .dll file). Partial definitions cannot span multiple modules.
- The class name and generic-type parameters must match on all partial-type definitions. Generic types can be partial. Each partial declaration must use the same parameter names in the same order.

For more information follow this link



0 comments

Post a Comment