Now in this tutorial we will see what
is partial class in C#, why use of partial class,difference between partial
class and class in C#.
Description:
What is
partial Class in C#? Difference between partial class and class?
In Object Oriented Programming it
is possible to 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. So a partial class is one which looks like a class
except it is defined in multiple files. To Split a class definition , use partial
keyword modifier.
Why we
use partial classes:
- This
feature allows us to write single class file into multiple files
so that multiple programmers can work at a time.
- When
working with automatically generated source, code can be added to class
without having to recreate the source file.
Partial
Class in C# with example:
Take a class and name it as part1.cs in
your console application project and write below.
1.
namespace OOPSProject
2.
{
3.
partial class Parts
4.
{
5.
public void Method1()
6.
{
7.
Console.WriteLine("Method 1");
8.
}
9.
public void Method2()
10.
{
11.
Console.WriteLine("Method 2");
12.
}
13.
}
14.
}
Take another class and name it part2.cs and
write below code.
- namespace OOPSProject
- {
- partial class Parts
- {
- public void Method3()
- {
- Console.WriteLine("Method 3");
- }
- public void Method4()
- {
- Console.WriteLine("Method 4");
- }
- }
- }
To test these two classes take another class and name it as testpart.cs and write below code .
- namespace OOPSProject
- {
- class TestParts
- {
- static void Main()
- {
- Parts p = new Parts();
- p.Method1(); p.Method2();
- p.Method3(); p.Method4();
- Console.ReadLine();
- }
- }
- }
Key
Points while writing Partial Classes in C#:
- All
the parts of the class must be defined within the namespace( same
assembly or same module).
- All
the parts must be used with partial keyword.
- All
the parts must be available at compile time to form the
final class.
- All
the parts must have the same accessibility level, such as public, private,protected
and so on. - if
any part of the class is declared as abstract then whole type is
considered as abstract in the same
manner for the sealed. - If
any part is declares a base type, then the whole type inherits
that class.
- partial modifier is
not available on delegate or enumeration declarations.
Conclusion:
I hope you got an idea on how to and
when to use partial classes with example and what precaution we should take
care while writing partial classes. I would love to take feedback from my
readers about my this writing.
- See more at:
http://aspdotnet-sekhar.blogspot.in/2013/07/parital-class-in-csharp-example-what-is-the-use-difference-to-class.html#sthash.aKmkKQUv.dpuf
No comments:
Post a Comment