Partial Methods in VS2008 and C# 3.0

.NET Musings

Partial Methods in VS2008 and C# 3.0

Technorati Tags: ,,,

VS2008 and C# 3.0 allow for the development of Partial Methods.This is one of the features that was long overdue.  A partial method allows for the signature definition in one file, and the implementation of that method in another file.

This comes into play in my world when I use CodeSmith to generate classes for me, as I do with NHibernate.  Before we cover that use case, there are some rules.

Partial methods:

  • Must be in a partial class (duh!)
  • Must return void
  • Are implicitly private

I always implement IDataErrorInfo in my POCO (Plain Old CLR Objects) for use in WPF applications.  I don't always have business logic to implement, but my codegen framework assumes that I will.

  1: partial void CheckForErrors(ref string errorInfo, string propertyName);

With the partial method stubbed out, I can write code that calls it.  If the method is not implemented, it doesn't end up in the IL.

  1: public virtual string this[string propertyName]
  2: {
  3:    get
  4:    {
  5:   string errorInfo = string.Empty;
  6:   CheckForErrors(ref errorInfo, propertyName);
  7:   return errorInfo;
  8:    }
  9: }
 10: 
 11: 

To flush out the method, I call something like this:

  1: partial void CheckForErrors(ref string errorInfo, string propertyName)
  2: {
  3:     StringBuilder sb = new StringBuilder();
  4:     switch (propertyName)
  5:     {
  6:         case "CategoryName":
  7:             if (CategoryName != null)
  8:             {
  9:                 if (CategoryName.Length > 50)
 10:                 {
 11:                     sb.Append("Invalid Length for CategoryName\r\n");
 12:                 }
 13:                 if (CategoryName.Contains("XXX"))
 14:                 {
 15:                     sb.Append("ModelName can not contain adult content!\r\n");
 16:                 }
 17:              }
 18:              break;

 19:     }
 20:     errorInfo = sb.ToString();

 21: }

Partial Methods allow for reduction of Cyclomatic Complexity in the main code branch.  No crazy if-then-else blocks or other hackery to determine if there needs to a call made to an implementing method.


And, as always, Happy Coding!

Comments are closed
Managed Windows Shared Hosting by OrcsWeb