Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

user-defined conversion to interface

Tags:

c#

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?

like image 702
Ben Collins Avatar asked Sep 05 '25 17:09

Ben Collins


1 Answers

Just make your implementations of IDepthFirstSearchTree<T> and IBreadthFirstSearchTree<T> explicit implementations. That way the members won't be available to be called directly on an expression of type Graph<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:

public IEnumerable<T> IterateBreadthFirst() { ... }
public IEnumerable<T> IterateDepthFirst() { ... }
like image 165
Jon Skeet Avatar answered Sep 09 '25 19:09

Jon Skeet