Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requirement to include reference to support an interface

Tags:

c#

interface

Assume that I have a library which defines an interface:

namespace LibraryOne
{
   public interface ISomething
   {
       void DoSomething();
   }
}

I implement this in a second library

namespace LibraryTwo
{
   public class Something : ISomething
   {
       public void DoSomething() { throw new Exception("I don't know how to do anything!"); }
   }
}

I then use this class in a third library

namespace LibraryThree
{
   public class MyClass
   {
      private Something myThing = new Something();
      public void DoIt() { 
          myThing.DoSomething();
      }
   }
}

Visual Studio tells me that LibraryThree has to have a reference to LibraryOne for this code to work. Even if I make ISomething internal and make LibraryOne InternalsVisibleTo LibraryTwo, I still have to have that reference. Why?

If I actually referred to an ISomething, I'd understand. If I expected Something to behave like an ISomething, I'd understand. But I just need to treat it as a Something.

like image 551
Bobson Avatar asked Feb 15 '23 21:02

Bobson


2 Answers

I just need to treat it as a Something

That's the thing: the moment you implement ISomething in Something, it becomes an ISomething too. The fact that a class implements an interface is integral to that classes nature.

Without this, you would be able to inherit Something to create SomethingElse, and that SomethingElse would not implement ISomething. Now consider this example:

public class Something : ISomething
{
    public void DoSomething() { ... }
    // Add this method
    public void ProcessSomething(Something other) {
        ISomething byInterface = other; // This is legal
        // Now do something with byInterface
    }
}

Your hypothetical code does this:

public class SomethingElse : Something {
   ...
}

Now pass an instance of SomethingElse to ProcessSomething to complete the circle: your SomethingElse is a Something but it is not ISomething, breaking the cast that C# expect to work unconditionally.

like image 74
Sergey Kalinichenko Avatar answered Feb 19 '23 15:02

Sergey Kalinichenko


When the CLR executes your application, it loads all the information about the types referenced in your program.

Because Something implements ISomething, the CLR needs to know about the interface - so the .dll containing this interface has to be accessible to the executable.

like image 26
Lawrence Avatar answered Feb 19 '23 15:02

Lawrence