Johnny5
Johnny5

Reputation: 6882

Interface reference across projects

I have 3 project : P1, P2 and P3

In P1, there is a definition of an Interface I

In P2, there is a Class C that implements Interface I

public class C : I
{
    ...
}

In P3, I have that method in a class:

public static C getC (int id)
{
   ...
}

At compile time, P3 does not compile because interface I is defined in a project that is not referenced. Why?

Note that I make no use of the interface in P3, I use the concrete class.

Upvotes: 0

Views: 1261

Answers (1)

James Michael Hare
James Michael Hare

Reputation: 38427

The reason is because the interface I is part of the public signature of C, thus when you use C it has to know about the interface definition as well. Thus it requires the assembly to be referenced.

To illustrate:

// Assembly 2
public class C : I
{
    ...
}

// Assembly 3 - needs definition of `I` from assembly 1 because part of `C`
// public definition.
public static C getC (int id)
{
   ...
}

Because I is publicly visible as a part of C (for example, you can assign a C to a reference of type I, etc), assembly 3 that wants to use C needs both the definition of C (assembly 2) and I (assembly 1)

However, if C used I internally (not visible to other assemblies), you wouldn't need to reference I's assembly to use C. For example:

// Assembly 2
public class C 
{
    private I _someInternalUseOfI = ...;
    ...
}

// Assembly 3 - Since in this case, `I` is only used privately in assembly 2,
// only assembly 2 needs the reference to `I` in assembly 1.
public static C getC (int id)
{
   ...
}

Does that make sense? Because a class's base classes and interfaces are part of its definition, they need to be known by any referencing assemblies. But if they are used internally but not visible externally, then they do not necessarily need to be known by any referencing assemblies.

Upvotes: 5

Related Questions