How do I program a partial class in C# in multiple files and in different namespaces?
-
32Anyone else find it amusing that a user named "Partial" is asking about partial classes? – lc. Jul 04 '09 at 00:58
-
1Why 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 Answers
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.

- 44,864
- 6
- 88
- 112
-
-
4Yes you can ... over multiple .cs files in the same assembly and over multiple assemblies as well. – JP Alioto Jul 04 '09 at 00:57
You cannot have a partial class in multiple namespaces. Classes of the same name in different namespaces are by definition different classes.

- 31,137
- 42
- 147
- 238
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()
{
}
}
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.
-
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