Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritence in C# and referencing a dll containing the base class

Tags:

c#

.net

reference

I have a scenario where the compiler is complaining that i am missing a needed reference.

I have 3 assemblies:

  • A.DLL

    • public class BaseClass
  • B.DLL (References A.DLL)

    • public class DerivedClass : BaseClass
  • C.DLL

    var derived = new DerivedClass();

In C.DLL i am only referencing B.DLL (i need access to DerivedClass only).

The compiler gives an error, saying i need to also reference A.DLL

This completely breaks the encapsulation, and i am not sure why this is needed (since B.DLL references A.DLL).

EDIT: Bad choice of words on "breaking encapsulation". My intention was this causes what seems to be an additional compile-time constraint on this project (C.DLL) since i am only instantiating types from B.DLL, and not from A.DLL.

I would want this compile-time requirement to be removed, mostly because B and C sit in the same solution, but A does not.

like image 887
lysergic-acid Avatar asked Jan 17 '23 00:01

lysergic-acid


1 Answers

This completely breaks the encapsulation, and i am not sure why this is needed (since B.DLL references A.DLL).

I don't see how it "completely breaks the encapsulation".

In order to perform member resolution, the compiler needs to know what's in BaseClass. Therefore to compile C.dll, you need references to both A.dll and B.dll. When someone is writing code accessing an instance of DerivedClass, they need to know what BaseClass supports, as it's likely to be a super-set of what DerivedClass itself overrides.

Even if you don't like it, that's just the way it is. If you don't want A.dll to be required at compile-time you could use composition instead of inheritance - but you'll still need A.dll at execution-time anyway.

like image 132
Jon Skeet Avatar answered Jan 18 '23 14:01

Jon Skeet