I just ran into the ‘user-defined conversions to or from an interface are not allowed’ problem in C#. What I was attempting to do was create a generic Graph class that could be iterated over in a couple different ways, depending on the supported interface. So:
public class Graph<T> : IBreadthFirstSearchTree<T>, IDepthFirstSearchTree<T> { // unnecessary details public static explicit operator IBreadthFirstSearchTree<T>(Graph<T> g) { g.enumerator = new GraphEnumerator<T>(g, SortStrategy.BreadthFirst); return g as IBreadthFirstSearchTree<T>; } public static explicit operator IDepthFirstSearchTree<T>(Graph<T> g) { g.enumerator = new GraphEnumerator<T>(g, SortStrategy.DepthFirst); return g as IDepthFirstSearchTree<T>; } }
was intended for this use:
foreach (GraphNode<T> gn in myGraph as IDepthFirstSearchTree) { // do stuff with gn }
Anyone know how I can achieve the same syntactic results within the constraints of the language?
Just make your implementations of
IDepthFirstSearchTree<T>andIBreadthFirstSearchTree<T>explicit implementations. That way the members won’t be available to be called directly on an expression of typeGraph<T>, but using ‘as’ (or a cast) the appropriate members will be available.I’m not sure that’s what I’d really do though – I’d probably get rid of the interfaces entirely and have: