Jami
Jami

Reputation: 589

why do an assembly with no direct dependency to another assembly have to reference it?

I'm quite new to c# programming. So lets assume we have two assemblies Asm1, Asm2 in which two classes are defined as Follows:

//Asm1
namespace ClassLibrary1
{
public class A//: B
  {
    B b = new B { i = 2};
    public int MyProperty { get { return b.i; } }
  }
}

//Asm2
namespace ClassLibrary2
{
  public class B
  {
    public int i;
  } 
}

Asm1 references Asm2 Now we have a runnable assembly say,asm3, that uses Asm1 with following piece of code:

//Asm3
A a = new A();
System.Console.Write(a.MyProperty.ToString());

the above codes compiles right with no error.

But things go wrong when we make little change in class A and have it inherited from class B. In this case line: A a = new A(); doesn't compile and produces error. But when we add asm2 as a reference to asm3 it works. please tell me why is that. why do an assembly ,with no direct dependency to another assembly, have to reference it? thanks in advance.

Upvotes: 1

Views: 214

Answers (2)

Dan Hunex
Dan Hunex

Reputation: 5318

Well if you did a project reference from Asm3 to Asm1, there is no need to reference the Asm2 to your project. During compilation, it will grab asm2 and put it in the bin folder. However, if you do direct binary reference of Asm1 in Asm3, it needs that asm2 either in bin( because asm1 needs it). This doesn't necessarily require to make a reference to asm2 but but it must be in bin of asm3. Thus, you don't need to do manual copy of Asm2 to bin, therefore you may reference it, it will copy it for you. However, I would do the following,

I will put Asm1, and Asm2 in a folder say dependencies ( for asm3), then I will reference only Asm1 in asm3, during build, asm2 will be copied to the bin directory and you will be good

So In short, your asm1 needs asm2 whereever it goes. That is why you needed it

Upvotes: 0

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61950

In this case the compiler requires access to the assembly where the base class of a type that you use (namely A), is declared. The exact rules are somewhat complex.

It is reported that with .NET 4.0 and Visual Studio 2010, if you in one assembly inherited a class from a second assembly which exposed types from an unreferenced third assembly (and your own project did not expose any of these types), it would work fine. But when upgrading to .NET 4.5 and Visual Studio 2012, the same code and reference combination fails, and you must refer the third assembly.

Upvotes: 2

Related Questions