Click here to Skip to main content
15,885,870 members
Articles / Programming Languages / C#
Tip/Trick

Multiple partial definitions for a class

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
17 Nov 2012CPOL1 min read 8.9K   52   7  
The tip shows an example for using multiple partial classes to define a single class.

Introduction

Partial definitions have been around for quite some time. A common scenario for partial classes is to separate the class code to two different cs files. For example, a Windows Forms form where Visual Studio generates separately the Designer.cs file to contain the generated code. 

However, the partial classes are not restricted only to two separate definitions. Actually there can be multiple partial definitions for a single class.

An example 

A simple example could be a data class, where the following parts are distinguished:

  • Data properties
  • Formatted data representation
  • Validations
  • Operations 

The data portion could look like the following:

C#
/// <summary>
/// Partial class definition for the data
/// </summary>
public partial class SomeClass {

   /// <summary>
   /// Property containing a text
   /// </summary>
   public string Text { get; set; }

   /// <summary>
   /// Property containing a number
   /// </summary>
   public int? Number { get; set; }
}

So few simple properties to hold the data. Now the formatting could be separated to a different definition.

C#
/// <summary>
/// Partial class definitions to format data
/// </summary>
public partial class SomeClass {
   /// <summary>
   /// Formats the text
   /// </summary>
   public string FormattedText {
      get {
         string returnValue = "";

         if (!string.IsNullOrEmpty(this.Text)) {
         returnValue = this.Text.Trim().ToLower();
         }

         return returnValue;
      }
   }

   /// <summary>
   /// Formats the number
   /// </summary>
   public string FormattedNumber {
      get {
         string returnValue = "";

         if (this.Number != null) {
            returnValue = ((int)this.Number).ToString("C2");
         }
         return returnValue;
      }
   }
}

The string is trimmed and represented as lower case while the number is show as a currency string. The validations could look like

C#
/// <summary>
/// Partial class containing the validations
/// </summary>
public partial class SomeClass {

   public bool Validate() {
      bool ok = true;

      ok &= this.CheckText();
      ok &= this.CheckNumber();

      return ok;
   }

   /// <summary>
   /// Checks that the text is defined if the number is not null
   /// </summary>
   /// <returns>True if validation is successful</returns>
   private bool CheckText() {
      bool ok = true;

      if (this.Number != null) {
         ok = !string.IsNullOrEmpty(this.Text);
      }

      return ok;
   }

   /// <summary>
   /// Checks that the number is between 0 and 50
   /// </summary>
   /// <returns>True if validation is successful</returns>
   private bool CheckNumber() {
      bool ok = true;

      if (this.Number != null) {
         ok = this.Number >= 0 && this.Number <= 50;
      }

      return ok;
   }
}

The validations check that the number is between 0 and 50 and if the number is defined (it's not null) the text is mandatory. And lastly the operations

C#
/// <summary>
/// Partial class containing the operations
/// </summary>
public partial class SomeClass {

   /// <summary>
   /// A method to write the data to console
   /// </summary>
   public void WriteToConsole() {

      if (!this.Validate()) {
         System.Console.WriteLine("Validaton failed");
         return;
      }

      System.Console.WriteLine(string.Format("Text is {0}", this.FormattedText));
      System.Console.WriteLine(string.Format("Number is {0}", this.FormattedNumber));
   }
}

This portion has a single method to write the data to the console if the validation succeeds.

So now we have a single class definition, which is split into four separate cs files. Calling the class could look like this 

C#
class Program {
   static void Main(string[] args) {
      SomeClass instance = new SomeClass();

      // Test invalid data
      instance.Number = 100;
      instance.Text = "1st definition";
      instance.WriteToConsole();

      // Test valid data
      instance.Number = 45;
      instance.Text = "2nd definition";
      instance.WriteToConsole();
   }
}

So when to use 

There's no single guideline when to use multiple partial definitions. Few possibilities could be:

  • Several parts of the class are generated and the code generation is done separately from each other
  • When the code has to be split, for example based on the usage and #region directive isn't satisfactory  
  • Different people work on different parts of a class simultaneously (possibly in a version controlled environment)  
The attached download contains the example project for this class. 

History 

  • November 17, 2012: Tip created. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Europe Europe
Biography provided

Comments and Discussions

 
-- There are no messages in this forum --