views:

439

answers:

5

I know that it's possible to have many classes in a namespace. Now, is it possible to have a class in more than one assembly (.dll file)?

+1  A: 

I think it is not posible. At most, you can spawn a class definition across multiple files in the same assembly (partial classes).

Konamiman
+4  A: 

No you can't span a class over multiple assemblies.
If you create Namespace1.Class1 in assembly1 & Namespace1.Class1 in assembly2, then you reference both assemblies in your project, you'll have:

  • 2 different classes
  • compile error (conflict): The type 'Namespace1.Class1' exists in both 'assembly1.dll' and 'assembly2.dll' ...
najmeddine
A: 

Theoretically it's possible. You can implement first part as a base class and second part as a derived class from the base. So let's sey you have class C having these methods:

class C {
  public A();
  public B();
}

In order to put implementation of A() in assembly X and put B() in assembly Y you can create these two classes instead:

assembly X:

class Z {
  public A();
}

assembly Y (references assembly X):

class C: Z {
  public B();
}

There you go. Class C would contain both methods A() and B(); If you want to split your implementation it's one of the ways.

ssg
Strictly speaking C is no longer a single class, however this solution may be what the original poster requires. Of course, if it was not possible to inherit from a base type in another assembly, then it would be practially impossible to create any program that used the .Net framework (or any other framework for that matter).
ShellShock
A: 

Why would you want to do this even if you could? What technical or business problem would be solved by doing this? .NET has partial classes that allow you to spread a class over multiple files if so desired. You can also extend behavior of classes using extension methods where you can define your methods in a separate assembly from the class you wish to extend.

Michael Mann
+1  A: 

If you define two classes in two separate namespaces, you have two distinct classes, existing in two distinct namespaces that have nothing whatsoever to do with each other. To the CLR, they look like this:

NamespaceA.ClassA
NamespaceB.ClassA

Even if you mark them partial, they are still distinct classes in separate namespaces. This is because namespaces are simply prepended to the name of the class when the class is compiled. Aside from that, the CLR is unaware of the notion of namespaces or partial classes. It's all compiler magic.

Clarification: When defining a partial type, you're defining a type. A type is never split across an assembly or a namespace.

Mike Hofer