TOC

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

Classi:

Partial Classes

If you have worked with C#, or perhaps even another programming language, you are used to the fact that the name of a class has to be unique - there cannot be two classes with the same name, unless they are in different namespaces. However, at one point, Microsoft decided to change this, with the introduction of something called partial classes.

Quando si definisce la propria classe con la parola chiave “partial”, è consentito estendere la funzionalità della classe con un'altra classe, che deve essere anch’essa dichiarata come parziale. Questo è utile nelle seguenti situazioni:

  • Quando hai una classe molto grande, puoi conservarla in più file, per rendere più facile lavorare con varie parti delle classi. Per esempio, si potrebbero tenere tutte le proprietà in un file e tutti i metodi in un altro file, pur avendo una sola classe.
  • Quando lavori con un designer, come quello di Visual Studio, dove tutto il codice del designer generato automaticamente può essere tenuto in un unico file, mentre il tuo codice è conservato in un altro 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!