1

I need to know an efficient way to handle one object at the time to control one of this 3 classes without the switch. (Knowing the object type at any point)

Note : The method AddVertex is not overloaded, so its common to the parent class.

            switch (User.Action)
            {
                case Actions.NewVertex:
                    switch (GraphsType)
                    {
                        case GraphsType.None:
                            Graph.AddVertex(p); /*This is the parent class*/
                            break;
                        case GraphsType.UndirectedGraph: 
                            UndirectedGraph.AddVertex(p); /*This is a  derived class*/
                            break;
                        case GraphsType.DirectedGraph: 
                            DirectedGraph.AddVertex(p); /*This is a  derived class,*/
                            break;
                    }
             }
2
  • what is it your trying to handle? the graph types? is AddVertex a static method? Commented Jul 8, 2013 at 22:07
  • Yes, the graph types , and no , its not a static method. Commented Jul 8, 2013 at 22:22

1 Answer 1

4

As I see, you just want to write user command handler.

There are no big problem. Just make a dictionary (var GraphsType -> Graph).

 var dictionary = new Dictionary<GraphsType, Graph>() {
     { GraphsType.None, GraphObject },
     { GraphsType.UndirectedGraph, UndirectedGraphObject },
     { GraphsType.DirectedGraph, DirectedGraphObject },
 };

And use it:

dictionary[GraphType].AddVertex(v);

If your Graph, UndirectedGraph, DirectedGraph are static classes, you must save in dictionary it's type (typeof(Graph)) and then on type use reflection to find method and invoke it (dictionary[GraphType].GetMethod(..).Invoke(...))

Sign up to request clarification or add additional context in comments.

1 Comment

Np. Well, In reality you even can make Dictionary between Actions and MethodNames and then call it with reflection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.