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.
- 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]
5: string errorInfo = string.Empty;
6: CheckForErrors(ref errorInfo, propertyName);
7: return errorInfo;
To flush out the method, I call something like this:
1: partial void CheckForErrors(ref string errorInfo, string propertyName)
3: StringBuilder sb = new StringBuilder();
4: switch (propertyName)
6: case "CategoryName":
7: if (CategoryName != null)
9: if (CategoryName.Length > 50)
11: sb.Append("Invalid Length for CategoryName\r\n");
13: if (CategoryName.Contains("XXX"))
15: sb.Append("ModelName can not contain adult content!\r\n");
20: errorInfo = sb.ToString();
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!