Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the C# reference dependencies different to VB?

Consider we have 3-tier app and have got three projects named P1, P2, P3.

Dependency: P1(Data) << P2(Business Logic) << P3(Presentation)

P2 has got a base class X that was inherited in an other class Y in P2. So, we add the ref P1 to P2. However, P3 uses P2.Y and doesn't use P1.X directly.

To do this we have to add ref P2 to P3. But there is a difference between VB and C#.

In VB, we add ref P2 only to P3. P2 uses P1 but it doesn't matters for P3. We don't need to add ref P1 to P3. This is enough!

But, in C#, we have to add ref P1 and P2 both to P3 even if the P3 doesn't use P1.X . If you don't add ref A to C you get the error below:

The type 'P1.X' is defined in an assembly that is not referenced. You must add a reference to assembly 'P1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

Why must we add two projects in C#?

Or, instead of this, can we block this behavior?

like image 332
Onur Gazioğlu Avatar asked Nov 13 '22 15:11

Onur Gazioğlu


1 Answers

A possible reason is that P2 publicly exposes members whose types are defined in P1. In that case P1 must be referenced in P3 too, even if you don't explicitly use it in P3.

Example:

// Assembly P1
public class C1
{
    ...
}

// Assembly P2
public class C2
{
    public string Foo { get; set; }
    public C1 Bar { get; set; }
}

// Assembly P3
void Main()
{
    C2 c = ...
    Console.WriteLine(c.Foo);
}

In the code above, P3 uses C2 (defined in P2), and C2 exposes a member of type C1 (defined in P1), so P3 must reference P1 (even if it doesn't use C2.Bar).


EDIT: actually I was wrong: you must reference P1 only if you do reference C2.Bar... The behavior is exactly the same in VB as in C#, I just tried (if you don't add the reference to P1 you get this error). If you previously didn't have this constraint in VB projects, it's only because P3 wasn't using anything that depended on P1.

like image 80
Thomas Levesque Avatar answered Dec 22 '22 07:12

Thomas Levesque