Simple question: does C#/Visual Studio have a way to tell the compiler, "if you know (at compile time) what "foo.IRenderable" is, add "foo.IRenderable" to the list of interfaces this class officially implements. Otherwise, forget I said anything about foo.IRenderable(and possibly, exclude one or more methods marked later in the source code from the class, because nothing is ever going to call them)"

Why:

I'm writing an editor extension for Unity3D that dumps the objects in the scene hierarchy to XML (primarily, for the purpose of making it easy to generate project documentation, not for persistence or passing objects around).

I'd like to define an Interface for my extension that someone using it can optionally implement in their own class and provide a custom renderer... in a way that doesn't force them to make my own extension a dependency of their class thereafter.

In other words, if their class is in a project that contains my library, Visual Studio will know what "foo.IRenderable" is, notice that THEIR class has a method like

public String renderThis(XmlElement parent) { ... }

and compile the class as one that officially implements foo.IRenderable, so that if an instance of it later gets passed to MY library, I can do something like this:

if (theirObject is foo.IRenderable) {
    addElement((foo.IRenderable)theirObject)
else
    addElement(theirObject.ToString());
}

... and have it recognize that theirObject is an IRenderable & cast it.

However, if someday their class ends up in a project that DOESN'T include my library, and Visual Studio has no idea at compile time what a foo.IRenderable is, it'll just compile it as normal without throwing an error, and if my class ended up someday testing it, it would fail the "is foo.IRenderable" test (since it wasn't marked as such at compile time).

0 Answers