I have a class library with all my database logic. My DAL/BLL.
I have a few web projects which will use the same database and classes, so I thought it was a good
Using Visual Studio 2015 and later it is possible to split partial classes across projects: use shared projects (see also this MSDN blog).
For my situation I required the following:
The following example demonstrates how partial classes and shared projects allow splitting classes over different projects.
In Class Library, Address.cs:
namespace SharedPartialCodeTryout.DataTypes
{
public partial class Address
{
public Address(string name, int number, Direction dir)
{
this.Name = name;
this.Number = number;
this.Dir = dir;
}
public string Name { get; }
public int Number { get; }
public Direction Dir { get; }
}
}
Class Library is a normal Visual Studio Class Library. It imports the SharedProject, beyond that its .csproj contains nothing special:
Library
Address.Direction
is implemented in the SharedProject:
namespace SharedPartialCodeTryout.DataTypes
{
public partial class Address
{
public enum Direction
{
NORTH,
EAST,
SOUTH,
WEST
}
}
}
SharedProject.shproj is:
33b08987-4e14-48cb-ac3a-dacbb7814b0f
14.0
And its .projitems is:
$(MSBuildAllProjects);$(MSBuildThisFileFullPath)
true
33b08987-4e14-48cb-ac3a-dacbb7814b0f
SharedProject
The regular client uses Address
including Address.Direction
:
using SharedPartialCodeTryout.DataTypes;
using System;
namespace SharedPartialCodeTryout.Client
{
class Program
{
static void Main(string[] args)
{
// Create an Address
Address op = new Address("Kasper", 5297879, Address.Direction.NORTH);
// Use it
Console.WriteLine($"Addr: ({op.Name}, {op.Number}, {op.Dir}");
}
}
}
The regular client csproj references the Class Library and not SharedProject:
Exe
{7383254d-bd80-4552-81f8-a723ce384198}
SharedPartialCodeTryout.DataTypes
The DbSetup uses only the enums:
The DbSetup.csproj does not reference Class Library; it only imports SharedProject:
Exe
To conclude:
Can you split a partial class across projects?
Yes, use Visual Studio's Shared Projects.
Is it a good idea to write a partial class in a separate project (creating a dependency) using the same namespace?
Often not (see the other answers); in some situations and if you know what you are doing it can be handy.