Is there a way to create a .NET public interface that cannot be implemented outside of an assembly?

To maintain binary backward compatibility in .NET, you cannot add new abstract methods to public classes and interfaces at all. If you do, then the code built against the old version of the assembly that extends / implements your class / interface will not work at runtime because it will not be able to fully extend / implement the new version. For classes, however, there is a convenient way:

public abstract class Foo {
    internal Foo() { }
}

      

Since Foo's constructor is internal, none of my assembly can extend Foo. This way, I can add new abstract methods to Foo without worrying about backward compatibility, since I know that no class in another assembly can extend Foo.

My question is, is there a similar trick for interfaces? Can I create a public interface and somehow ensure that no one in my assembly can create an implementation of it?

+3


source to share


2 answers


No, you cannot do this. But then, given that the point of the interface is to define the behavior of the implementation by defining the contract, it makes sense.

However, you can create internal interface

one that inherits from yours public interface

:

public interface IPublicInterface {
    /* set-in-stone method definitions here */
}

internal interface IChildInterface : IPublicInterface  {
    /* add away! */
}

      



This should prevent any backward compatibility issues with other assemblies, while still allowing additional methods to be hidden.

The downside, of course, is that you will have to remember how IChildInterface

when you need it, instead of just using it likeIPublicInterface

That said, to be honest, if you really wanted to define some assembly-only functions, but still require the end user to define their own implementations for some of the methods, your best bet is probably an abstract class.
+3


source


No, you cannot.

But since in IL, an interface is just a pure abstract class (i.e. one with no implementation at all), you can use the technique you already described and it will be pretty much the same.

As noted, keep in mind that this approach restricts your type to inherit only from the fake "abstract class" interface. It can implement other interfaces, but it cannot inherit from any other type. This may or may not be a problem, depending on the scenario.



If you think you are better at design, name your pure abstract class following the .NET standard for interfaces. For example. IFoo

instead of Foo

.

Of course, this implies the question: why do you want to do this? If you don't have an implementation at all, what harm could be caused by other code being able to implement your interface?

But as a practical matter, you can enforce your rules the way you want them to.

0


source







All Articles