Partial classes and C#
Microsoft added the concept of partial classes to C# 2.0 (along with the arrival of the .Net Framework 2). With the .Net implementation, you can split a class into multiple source files, and/or multiple locations in the same source file so long as they are all in the same namespace. All parts must use the same base class so it's typical to indicate the base class in only the first part. All other parts don't need to specify the base class. All the parts included at compile time are compiled. This presents some interesting possibilities.
.Net Features
- Parts can specify different base interfaces, and the final type implements all of the interfaces listed by all of the partial declarations.
- Any class, struct, or interface members declared in a partial definition are available to all of the other parts.
.Net Limitations
- All parts must be defined within the same namespace.
- All the parts must use the partial keyword.
- All of the parts must be available at compile time to form the final type.
- All the parts must have the same accessibility (i.e. public, private, etc.).
- If any of the parts are declared abstract, then the entire type is abstract.
- If any of the parts are declared sealed, then the entire type is sealed.
- If any of the parts declare a base type, then all parts use that same base type. All parts that specify a base class must specify the same base class. You can omit a base class in one or more of the parts in which case the part still uses the same base class.
Visual C# 2008 Working Winforms Example
The following simple example demonstrates partial classes.
Create a form and place a button on it and add code as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Partial
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Cyborg MyRobot = new Cyborg();
//Optionally set CyborgName property:
//MyRobot.CyborgName = "Cameron";
MyRobot.IntroduceYourself();
}
}
//
//One use of partial classes is to organize
//large classes into logical groups. For example,
//you can use partial classes to separate your
//class properties and methods. Although these
//are in the same file, you could put them in
//separate source files.
//
//Cyborg Properties...
public partial class Cyborg : System.Object
{
public string CyborgName { get; set; }
}
//Cyborg Methods...
public partial class Cyborg : System.Object
{
public virtual void IntroduceYourself()
{
if (CyborgName == null)
MessageBox.Show("Hi, I do not have a name yet.");
else
MessageBox.Show("Hi, my name " + CyborgName + ".");
}
}
}