Partial Class

C#.NET

From Partial Class Definitions at MSDN, 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. There are several situations when splitting a class definition is desirable:

  • 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.
  • To split a class definition, use the partial keyword modifier

Here I wanna point out the third point. There is sometimes we will work on a large class file which contains a large numbers of LoC(Line of Code). If you have such class, I bet it is harder to maintain one large class file instead of some distributed and linked source code file that can be compiled into one compiled code.

Here is some demo. Create file CoOrds1.cs in any folder you prefer. Then write this code.

public partial class CoOrds
{
    private int x;
    private int y;

    public CoOrds(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

Create file CoOrds2.cs in the folder you already put CoOrds1.cs

public partial class CoOrds
{
    public void PrintCoOrds()
    {
        System.Console.WriteLine("CoOrds: {0},{1}", x, y);
    }

}

Finally, create a class to execute our CoOrds class in TestCoOrds.cs in the folder that you’ve put both the two files before.

class TestCoOrds
{
    static void Main()
    {
        CoOrds myCoOrds = new CoOrds(10, 15);
        myCoOrds.PrintCoOrds();
    }
}

Open Command Line Interpreter and write this command on the CLI.

csc CoOrds1.cs CoOrds2.cs TestCoOrds.cs

On the CLI, type TestCoOrds.exe and the result would be printed out to the console screen.

Java

No. Java source codes can not be split across multiple files. Not until know.

2 comments… read them below or add one

Neki Arismi January 9, 2012 at 15:36 pm

C#.NET bisa buat bikin apaan aja sih kk?
*komen, sekalian setor muka*

ganda January 9, 2012 at 15:37 pm

#Neki Arismi:
Bisa buat Mobile, Web maupun Desktop. :)

Leave a Comment