0

I was wondering if there is a way to implement next example :

string tmp = "+";
int ans1 = 4 tmp 5;
tmp = "+";
int ans2 = 4 tmp 5;

Thanks

Igal
  • 4,603
  • 14
  • 41
  • 66
  • 1
    Why do you want to do that? If you want to build/parse expression trees, there are better ways. –  Feb 05 '11 at 20:11

3 Answers3

4

You can do this at least:

MyOpType tmp = "+";
int ans1 = 4 & tmp & 5;
tmp = "+"; // Could be any operator implemented by MyOpType
int ans2 = 4 & tmp & 5;

By creating a class called MyOpType which have implicit operator overloading from string to it self. This would also have to operator overload & to return some operator type which miss a single argument.

However, I do not recommend doing such "hacks" because it is not clear what the code does. And furthermore, I'm sure there is a better way to do what you what to do. So if you explain the context then we might find a better solution :)

I guess something like Result("+", 4, 5) would be cleaner and easier to implement. This leads me to the question: Where do you get the operator from? users? If not, a better solution can surely be found. If you want some form of "dynamic interpretation" then .Net Expressions trees could be interesting.

Lasse Espeholt
  • 17,622
  • 5
  • 63
  • 99
  • Thanks for the answer. I've XML file which i desirialize from. (math questions) and i need to compute result of the question. currently i implemented this part by 4 ugly switch/case statements. therefore i was wondering if i can implement it more clearly. (the operator variable is dynamic, and i avoid switch/case statement)... any better solution ? :) Thanks – Igal Feb 05 '11 at 23:48
  • @user301639 Hhm so you switch on a variable which is +,- etc. and what to make a better solution? If so, no, see http://stackoverflow.com/questions/4763798/can-operations-be-generalized/ The problem is, how should C# know what the different operators should do? It can't because you could assign different meaning to them. You could use an existing library for parsing these things (I think it will appear in the next version) but this just hides the switch (or a uglier solution) but does not remove it :) – Lasse Espeholt Feb 06 '11 at 08:34
0

In exact that syntax - NO. Using some other syntax (closer to C#) - maybe

Snowbear
  • 16,924
  • 3
  • 43
  • 67
0

This subject called by "expression", there are many sample about it. the best one here

Good luck

Nuri YILMAZ
  • 4,291
  • 5
  • 37
  • 43