TOC

This article is currently in the process of being translated into Vietnamese (~26% done).

Classes:

Partial Classes

Nếu bạn đã từng làm việc với C#, hoặc là đã có trải nghiệm với vài ngôn ngữ lập trinh khác, thì chắc hẳn bạn sẽ quen với một điêu hiển nhiên rằng là tên của 1 class phải là duy nhất - một chường trình không thể tồn tại hai class với cùng 1 tên, trừ phi hai class đấy nằm ở các namespace khác nhau. Nhưng vào một ngày đẹp trời, Microsoft đã quyết định một lối đi riêng, với việc giới thiệu một thứ có tên là Partial Classes.

When you define your class with the partial keyword, you or someone else is allowed to extend the functionality of your class with another class, which also needs to be declared as partial. This is useful in the following situations:

  • When you have a very large class - you can then keep it in multiple files, to make it easier to work with various parts of the classes. For instance, you could have all the properties in one file and all the methods in another file, while still just having one class.
  • When you work with a designer, like the one in Visual Studio - for instance with WinForms, where all the automatically generated designer code can be kept in one file, while your code is kept in another file.

Let me illustrate this with an example. In my project, I have the usual Program.cs, found in a console app. Besides that, I have added two files: PartialClass1.cs and PartialClass2.cs. Here are the files and their contents:

PartialClass1.cs

using System;

namespace PartialClasses
{
    public partial class PartialClass
    {
public void HelloWorld()
{
    Console.WriteLine("Hello, world!");
}
    }
}

PartialClass2.cs

using System;

namespace PartialClasses
{
    public partial class PartialClass
    {
public void HelloUniverse()
{
    Console.WriteLine("Hello, universe!");
}
    }
}

Notice that both classes are defined with the partial keyword and have the same names. Also notice that each of them define a method - HelloWorld() and HelloUniverse(). In our Program.cs we can now use this class as if it was defined in only one place, just like any other class:

using System;

namespace PartialClasses
{
    class Program
    {
static void Main(string[] args)
{
    PartialClass pc = new PartialClass();
    pc.HelloWorld();
    pc.HelloUniverse();
}
    }
}

Summary

With partial classes, you can split your classes into multiple files, either because the class definition is very large or when the tools you work with benefits from it, like with the Visual Studio designer for WinForms.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!
Table of Contents