Partial Class:
There are many situations when you
might need to split a class definition, such as when working on a large scale
projects, multiple developers and programmers might need to work on the same
class at the same time. In this case we can use a feature called Partial Class.
C# provides the ability to have a
single class implementation in multiple .cs files using the partial modifier
keyword. Each source files contains a section of the definition of class. When
partial code is compiled on CLR, multiple classes or interfaces or struct with
partial keyword will be compiled into single unit or it is considered as single
class, interface and struct. All classes should be declared
under one namespace scope only.
Suppose you have a "Student" class. That
definition is divided into the two source files "Student1.cs" and
"Student 2.cs". Then these two files have a class that is a partial
class. You compile the source code then create a single class.
Advantages of Partial
Class:
- Separate UI design code and business logic code for ease of working and understanding.
- Multiple developers can also work simultaneously like one creating logic and other working on designer part.
- It is also helpful to embed our custom logic code under framework auto generated code.
- Larger classes can be split into smaller classes for easy to understand and maintain.
- Interfaces can also split into multiple code to share it with multiple developers which further help in fast application development.
There are some points
that you should be when you are developing a partial class in your application:
- You need to use partial keyword in each part of partial class.
- The name of each part of partial class should be the same but source file name for each part of partial class can be different.
- All parts of a partial class should be in the same namespace.
- Each part of a partial class should be in the same assembly or DLL, in other words you can't create a partial class in source files of a different class library project.
- Each part of a partial class has the same accessibility.
- If you inherit a class or interface on a partial class then it is inherited on all parts of a partial class.
- If a part of a partial class is sealed then the entire class will be sealed.
- If a part of partial class is abstract then the entire class will be an abstract class.
Example:
PartialClassFile1.cs:
public
partial class MyPartialClass
{
public MyPartialClass()
{
}
public void Method1(int val)
{
Console.WriteLine(val);
}
}
PartialClassFile2.cs:
public
partial class MyPartialClass
{
public void Method2(int val)
{
Console.WriteLine(val);
}
}
MyPartialClass
in PartialClassFile1.cs defines the constructor and one public method, Method1,
whereas PartialClassFile2 has only one public method, Method2.
Prof. Shardul P. Patil
profshardulp.patil@gmail.com
No comments:
Post a Comment