Understanding and Using Partial Classes in C#
page 3 of 8
by Brendan Enrick
Feedback
Average Rating: 
Views (Total / Last 10 Days): 8427/ 436

Creating Partial Classes

As I've mentioned, partial classes allow you to separate code for a class into multiple class definitions. So as an example I will write a few class definitions. One will be a whole definition of a class without using partial classes, and the other one will be the same class split into two partial classes. Observe here my single definition class of AIPlayer.

Listing 1: A Standard Class

public class AIPlayer
{
  public AIPlayer()
  {
    // Construct your class here.
  }
  public Move GetMove()
  {
    // Choose the best move and return it.
  }
}

In this simple example I've defined a basic constructor as well as one simple method. Not much, but we don't need to have a lot for our example here. The important thing to note here is the possibility to create these classes and how they work. So notice on the next one how we will separate these two methods, the constructor and the GetMove function, into two separate class definitions.

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.
  }
}

Without having the partial keyword in there I would probably get a compiler error. The reason for this is that I would be declaring two different classes in the same namespace with the same name, and that would generate the error. Since I have the partial keyword there, the compiler knows that I am just extending the existing class. It will take that into account and will combine the code before trying to compile it.

As a note, make sure to use the partial keyword on ALL definitions of the class even the original one. This is not necessary for VB, but in C# all of the classes must have the partial keyword. I think it is great that this is included, because it is a hint to a programmer that there might be another piece of a class somewhere else. If you ever see the partial keyword on classes you're working with, it is a nice warning that there might be more to the class elsewhere.


View Entire Article

Article Feedback

Title:  
Name:  
Url: ( Optional )
Comment:  
Please add 1 and 5 and type the answer here:

User Comments

Title: not decribe well   
Name: vivek rai
Date: 5/4/2008 7:21:53 AM
Comment:
u r not able to decribe well....

Product Spotlight
Product Spotlight 
Learn More
.NET Tools
asp.net shopping cart
asp.net chart control






Ads Powered by Lake Quincy Media
Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2008 ASPAlliance.com  |  Page Processed at 7/4/2008 5:55:32 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search