Wednesday 25 December 2013

Partial class in C#

Partial class is a new feature added to C# 2.0 and Visual Studio 2005. It is supported in .NET Framework 2.0. If you are working with .NET 1.0 or 1.1, partial classes may not work. 
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.

When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.

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 creating Windows Forms, Web Service wrapper code, and so on. You can create code that uses these classes without having to edit the file created by Visual Studio.

Benefit of partial classes:

1) More than one developer can simultaneously write the code for the class.

2) You can easily write your code (for extended functionality) for a VS.NET generated class. This will allow you to write the code of your own need without messing with the system generated code.

There are a few things that you should be careful about when writing code for partial classes: 
  • All the partial definitions must proceeded with the key word "Partial".
  • All the partial types meant to be the part of same type must be defined within a same assembly and module.
  • Method signatures (return type, name of the method, and parameters) must be unique for the aggregated typed (which was defined partially).
  • The partial types must have the same accessibility.
  • If any part is sealed, the entire class is sealed.
  • If any part is abstract, the entire class is abstract.
  • Inheritance at any partial type applies to the entire class.
I have attached code of the partial classes along with this article. You can open the project and understand the functionality.

Hope the article would have helped you in understanding what partial classes are. Waiting for your feedback.
Example
//partial class


public partial class Student

{
public virtual void GetRollNo();
}

public partial class Student
{
public virtual void GetStudentName();
}

//Derived class

public class School : Student
{
public void getStudentDetails()
{
GetRollNo();
getStudentDetails(); 
}
}

2 comments:

  1. Have a look at this link http://www.etechpulse.com/2014/04/c-tutorial-about-partial-class-in-c.html

    ReplyDelete

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...