Tuesday 15 December 2009

Using Partial Classes to expose methods that are client, server or shared

Before the invention of shared classes this code would have been made by inheriting shared functionality from a base class. Here is another way of sharing functionality from a shared class:

This class if for shared methods for both client and server
namespace SharedPart
{
    public class Class1
    {
        public void SharedF1()
        {
        }
    }
}

This is an extension to the shared class for methods that are for clients only
using SharedPart;
namespace ClientPart
{
    public static class Class1Extension
    {
        public static void ClientF1(this Class1 c1)
        {
        }
    }
}

This is an extension to the shared class for methods that are for servers only
using SharedPart;
namespace ServerPart
{
    public static class Class1Extension
    {
        public static void ServerF1(this Class1 c1)
        {
        }
    }
}

ion

Here is how to consume the client and shared parts
using SharedPart;
using ClientPart; // By commenting these out restricts the functionality visible in Class1namespace Client
{
    static class Program
    {
        static void Main()
        {
            Class1 c = new Class1();
            c.SharedF1();
            c.ClientF1();

        }
    }
}

Using partial classes in this way is not always the best approach because it does not lend itself to implementation in interfaces. Often the inherited way is better because the resulting code is more structured. But this is an interesting method to extend functionality of an existing class.