Create a mathematical symbol in C#?

Hi!

I’m looking for a way to dynamically define a mathematical sign. For example, let’s say I’m adding 2 numbers:

Answer = NumberOne + NumberTwo;

Now, if I want to switch the “+” to a “-”, I currently do this:

bool IsPlus;
IsPlus = true;
if(IsPlus)
    Answer = NumberOne + NumberTwo;
else
    Answer = NumberOne - NumberTwo;

To me, that looks pretty dumb. There’s got to be a smarter way to do this! I found Math.Sign, but that’s not what I’m looking for, that’s just to get the sign of a number.

Hi,

what about this;

var multiplier = IsPlus? 1 : -1;
Answer = NumberOne + multiplier * NumberTwo;

Note:
multiplier = IsPlus? 1 : -1;
is equal to
if(isPlus){
multiplier = 1;
}else{
multiplier = -1;
}

Not sure I understand exactly what you’re asking. But there’s not really anything wrong with doing code like what you show, assuming you have a function in which can either add or subtract.

There are probably ways to condence it a bit but it’d also make it less obvious what you’re doing so just keep it as is.

What’s the overall purpose? Do you need more operations? Who or what does influence the decision which operator to use?

You could outsource this into a helper method with a parameter which indicates the operation to execute, or abstract that all by using delegates or your own interface like ‘IBinaryOperation’.
Under certain conditions, you could assign a new delegate or a different implementation to the variable that holds an operation instance.

If it’s just about Plus and Minus, I’d just to do it the way you’ve already done it.

Thanks for the replies. This is currently what I’m doing:

transform.position = Vector3.Lerp(transform.position, new Vector3(Player.position.x + Offset.x, transform.position.y - DodgeDistance, Player.position.z + Offset.z), smooth);

And I often have to change the sign before DodgeDistance into a + or -. That’s why I was concerned with my method of handling that, but I guess there’s not much to improve.

I’d double check the code that sets DodgeDistance and see if it’s better to set the negative there, so later you can always add it.

bool IsPlus;
IsPlus = true;
if(!IsPlus)
    NumberTwo *= -1;
Answer = NumberOne + NumberTwo;