13

How do I program a partial class in C# in multiple files and in different namespaces?

Partial
  • 9,529
  • 12
  • 42
  • 57
  • 32
    Anyone else find it amusing that a user named "Partial" is asking about partial classes? – lc. Jul 04 '09 at 00:58
  • 1
    Why would you want to be able to do this? What problem have you encounter that you think such a feature would help you solve? – jason Jul 04 '09 at 01:00
  • It's really just a coincidence. I have been on stackoverflow for a couple of weeks. – Partial Jul 04 '09 at 01:02
  • @Jason: I just wanted to know how I could spit my code in multiple files. I am rather new to C# (from a C++ background). – Partial Jul 04 '09 at 01:06
  • It's the "different namespaces" part that I'm questioning. – jason Jul 04 '09 at 12:28

4 Answers4

32

You can't. From here ...

Using the partial keyword indicates that other parts of the class, struct, or interface can be defined within the namespace

Must be in the same namespace.

Per comment: Here's an article that discusses defining a namespace cross multiple assemblies. From there ...

Strictly speaking, assemblies and namespaces are orthogonal. That is, you can declare members of a single namespace across multiple assemblies, or declare multiple namespaces in a single assembly.

JP Alioto
  • 44,864
  • 6
  • 88
  • 112
11

You cannot have a partial class in multiple namespaces. Classes of the same name in different namespaces are by definition different classes.

C. Ross
  • 31,137
  • 42
  • 147
  • 238
4

A partial class (as any other class) needs to live in one single namespace (otherwise its another class).

To split it between different files just use the partial keyword after the access keyword:

// this bit of the class in a file
public partial class Employee
{
    public void DoWork()
    {
    }
}

//this bit in another file
public partial class Employee
{
    public void GoToLunch()
    {
    }
}
lc.
  • 113,939
  • 20
  • 158
  • 187
JohnIdol
  • 48,899
  • 61
  • 158
  • 242
3

You can't. A partial class means just that: A single class broken into several files. That also means that all files that this partial class consists of must have the same namespace. Otherwise it wouldn't be the same class anymore.

lc.
  • 113,939
  • 20
  • 158
  • 187
Joey
  • 344,408
  • 85
  • 689
  • 683
  • Why the downvote? This is correct, especially the "Otherwise it wouldn't be the same class anymore" bit. – lc. Jul 04 '09 at 01:00