Code Structure with VS2005 Using Partial Classes

Thanks to Trent on suggesting to use a partial class for implementing the auto-code part of a class from yesterday. I thought the idea of partial classes was neat but the only thing I could think of was where you had a large class so you split it up into logical components for multiple people to work on at the same time. Personally I wouldn't let my classes get that big but you never know on a large system. However it seems perfectly suited for this type of separation. Okay, maybe so I'm not the first to explore things to do with partial classes when you're bored. Cut me some slack for being a year late to catch up on things and check out:

Making Sense of Partial Classes
Create Elegant Code with Anonymous Methods, Iterators, and Partial Classes
Understanding and Using Partial Classes

Here's a sample class split up into two files. UserCG.cs and User.cs. One is for interacting with the Class Designer and the code it generates. The other is for hand coding your Domain logic.

/// <summary>

/// This part of the class has the code generated fields and properties.

/// </summary>

public partial class User

{

    public User()

    {

    }

 

    private string name;

    public string Name

    {

        get

        {

            return name;

        }

        set

        {

            name = value;

        }

    }

 

    private string emailAddress;

    public string EmailAddress

    {

        get

        {

            return emailAddress;

        }

 

        set

        {

            emailAddress = value;

        }

    }

}

 

/// <summary>

/// This part of the class has the coding implementation.

/// </summary>

public partial class User

{

    public void DomainMethod()

    {

    }

}

 

It's not perfect as you may want to use the Designer to add a bunch of methods that should be in the Domain logic but then you could just add those by hand and keep your fields, properties and interface implementations in the UserCG.cs file. Just right click on the Class in the Designer, choose Properties, then specify which source file any new members added to the class will be added to through the New Member Location property. So now you can keep all the frilly stuff out and put your Domain logic in a single file for your class. Of course some people will recognize this as it takes me back to the old days when we had an Implementation and Interface file from our Delphi/Turbo Pascal days. Very slick none the less.

No Comments