Friday, April 16, 2010

Partial Classes in C#

A class defined in two or more files is called a partial class. The keyword partial is used to define the class. When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously. During compile time all the partial class are compiled into one type only.


Listing 1: A Standard Class
public class AIPlayer
{
public AIPlayer()
{
// Construct your class here.
}
public Move GetMove()
{
// Choose the best move and return it.
}


Listing 2: A Class Split Into Two Partial Classes
public partial class AIPlayer
{
public AIPlayer()
{
// Construct your class here.
}
}
public partial class AIPlayer
{
public Move GetMove()
{
// Choose the best move and return it.
}
}

ASP.NET Pages Already Use Partial Classes

First I will remind you again of the ASP.NET pages. Every page you create in ASP.NET is eventually compiled. Every .aspx file will be used to declare a page class. They all inherit from a standard Page class. You can see this in your code behind file. If you view the code of your ASP.NET page you will see a class definition. It will have the partial keyword in the definition and it will look similar to this code.

Listing 3: Codebehind File
public partial class MyWebPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Perform some action here.
}
}


0 comments: