6.8. Organizing Your Interface Implementations

Problem

You have a class that implements an interface with many methods. These methods support only the interface functionality and don't necessarily relate well to the other code in your class. You would like to keep the interface implementation code separate from the main class code.

Solution

Use partial classes to separate the interface implementation code into a separate file. For example, you have a class called TriValue that takes three decimal values and performs some operations on them, such as getting the average, the sum, and the product. This code is currently in a file called TriValue.cs, which contains:

	public partial class TriValue
	{
	    public decimal First { get; set; }
	    public decimal Second { get; set; }
	    public decimal Third { get; set; } 
	    public TriValue(decimal first, decimal second, decimal third)
	    {
	        this.First = first;
	        this.Second = second;
	        this.Third = third;
	    }

	    public TypeCode GetTypeCode()
	    {
	        return TypeCode.Object;
	    }

	    public decimal Average
	    {
	        get { return (Sum / 3); }
	    }

	    public decimal Sum
	    {
	        get { return First + Second + Third; }
	    }

	    public decimal Product
	    {
	        get { return First * Second * Third; }
	    }
	}

Now, you want to add support for the IConvertible interface to the TriValue class so that it can be converted to other data types. We could just add all 16 method implementations to the class definition in TriValue.cs and hide the code using a #region statement. Instead, you can now use the partial keyword on the TriValue class ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.