tags:

views:

68

answers:

2
 private delegate int Operate(int x, int y);
 Operate usedOperator;

 int Add(int x, int y)
 {
  return x + y;
 }

usedOperator.ToString() should return either "+" "-" or whatever method the delegate currently contains. Is this possible somehow?

EDIT: Alternatives to the delegate approach would be fine too. I basically am writing a program that asks the user some math questions with randomized numbers and operators.

+1  A: 

You can't override members of a delegate, but you could achieve what you want with expressions:

Expression<Func<int, int, int>> expr = (a, b) => a + b;
Console.WriteLine(expr.Body.ToString()); // prints "(a + b)"
Thomas Levesque
+1  A: 

Why not use inheritance & polymorphism.
Create an abstract class MathOperation and create multiple classes that implement MathOperation, e.g. AddOperation, SubtractOperation and so on. You can override ToString() in these classes.
In your code you should have:


MathOperation operation = new AddOperation(x, y); // or new MultiplyOperation(x, y);
operation.Perform(); // This will perform addition
operation.ToString(); // This will print "+"
sh_kamalh
Oh God, sometimes you just don't see the obvious anymore. Of course you are right. Oh my... THANKS.
Blub