Click here to Skip to main content
Click here to Skip to main content
Go to top

Multiple partial definitions for a class

, 17 Nov 2012
Rate this:
Please Sign up or sign in to vote.
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:

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

   /// <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

   /// <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

   /// <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 

   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)

Share

About the Author

Mika Wendelius
Architect
Finland Finland
I've been a programmer since mid 80's using languages like assembler, C/C++, PL/I (mainframe environment), pascal, VB (I know, I know, no comments please) and C# and utilizing different techniques and tools.
 
However I'm specialized in databases and database modeling. Mostly I have used products like Oracle (from version 6), SQL Server (from version 4.2), DB2 and Solid Server (nowadays an IBM product).
 
For the past 10+ years my main concerns have been dealing with different business processes and how to create software to implement and improve them. At my spare time (what ever that actually means) I'm also teaching and consulting on different areas of database management, development and database oriented software design.

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140926.1 | Last Updated 17 Nov 2012
Article Copyright 2012 by Mika Wendelius
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid