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
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.
In exact that syntax - NO. Using some other syntax (closer to C#) - maybe
This subject called by "expression", there are many sample about it. the best one here
Good luck
Related
This question already has an answer here:
Put bool comparison operator in variable
(1 answer)
Closed 1 year ago.
Is there a way to use a variable in place of an operator? Such as:
char additionSign = '+';
int number = 1;
int number2 = 1;
Console.WriteLine(number additionSign number1);
I know this code won't work, but is there a way to do this another way?
That exact syntax does not work, no.
But you can make a delegate taking two ints and returning and int, for which you could pass any lambda.
Func<int, int, int> oper;
oper = (a, b) => a + b; // addition lambda
oper = (a, b) => a - b; // subtraction lambda
oper = (a, b) => a * b; // multiply lambda
Console.WriteLine(oper(number, number1));
you can use something like this ... you can add different operator if you wants
var operator = {
'*': function(a, b) { return a * b },
'<': function(a, b) { return a < b },
// ...
};
var op = '*';
alert(operator[op](10, 20));
You're fundamentally changing the syntax of the C# language. You're introducing the idea of a binary operator alias. Interesting, I won't ask why you want to do that. Instead, I will say that you probably want to look into a DSL or domain-specific language transpiler engine. In the same way that languages like TypeScript transpile to JavaScript, you could make a language that would compile to C#. The language you're talking about could alias anything it wanted to.
I was browsing around stack overflow and I encountered this question:
check for duplicate filename when copying files in C#
In this question, this little gem existed:
int i = +1
I have never seen this syntax before. So I opened up the interactive C# window in visual studio:
Microsoft (R) Roslyn C# Compiler version 1.3.4.60902
Loading context from 'CSharpInteractive.rsp'.
Type "#help" for more information.
> int i = +1;
> i
1
> +1 == 1
true
Is this similar to +=? Is this some new syntax? What is this operator? How is it different than a normal variable declaration?
That's the unary plus operator. From the documentation:
The result of a unary + operation on a numeric type is just the value of the operand.
In most sane contexts1 where you're writing code, it'll be optional (+1 is the same as 1 if we're writing literals).
It mostly exists for symmetry with the unary minus operator.
Most of the time, you'll not write code containing it, but if you're generating code it can be handy to be able to apply a unary operator either way2.
It has no relation to +=.
1Insane code could override this operator for custom types and make it more than a no-op. But I'd love to understand a use case where it makes code more understandable, which should be the main aim of most code.
2E.g. imagine you're chaining a set of operations together and for each additional element, you wish to change the sign of the overall result. This lets you just store an operator and apply it blindly when you finally decide to output a result
For for all signed numeric types the positive-sign is optional. So,
+1 == (+1) == 1
+1.0 == (+1.0) == 1.0
+1L == (+1L) == 1L
+1.0m == (+1.0m) == 1.0m
Do not confuse
int i = +1; // Assigns 1
which is the same as
int i = (+1); // Assigns 1
or simply
int i = 1; // Assigns 1
with
int i += 1; // INCREMENT!
which increments i.
In C# terms there is a binary + operator (the addition operator as in int i = 3 + 4;) and a unary + operator (the plus sign as in int i = +1;).
Think of it the way you think of
int i = -1
and it becomes obvious
Is there a way to covert from bool to integer without a conditional statement (e.g., if-statement)?
int intValue = boolValue ? 1 : 0;
No, there is not. You may hide this conditional behind additional method calls like Convert.ToInt, or prefer a different syntax like an actual if but in the end, somewhere, there will be your conditional.
int intValue = Convert.ToInt32(boolValue));
Use Convert.ToInt32(boolValue)
Despite the fact that nvoigt's answer is perfectly correct I can give you a few more examples JUST FOR FUN
NEVER! NEVER USE THIS CODE! IT IS PROVIDED JUST FOR FUN OR TO RESOLVE A DISPUTE WITH A (GOOD) FRIEND!)
At first method GetHashCode does the magic (as an implementation detail):
bool b = true;
int i = b.GetHashCode();
If you want some more esoteric approach.. hm.. you're welcome):
bool b = true;
int i = ~(b.ToString()[0] / 2) & 1;
REMEMBER! NEVER!
Example:
We found this is some vendor written code and we're trying to figure out why they'd do this.
bool tmp = false;
if (somecase)
tmp = true;
if (someOtherCase)
tmp |= true;
For no good reason at all. A boolean value |= true will always be true. This is someone trying to be fancy, or forgetting boolean logic =)
Change it to tmp = true;.
Perhaps one of the boolean literals used to be a variable, and they just didn't think to change the operator when they changed the operand. Obviously the logic is equivalent.
More likely, they were thinking that in the second case, they want to retain the result of evaluating the first "if" condition. Of course, that's false reasoning.
A simpler equivalent statement:
bool tmp = somecase | someOtherCase;
EDIT
As pickypg notes, this statement could be confusing, since most people don't expect | with boolean values, and many won't notice it, or won't think about the implications for side effects. The best way to be explicit (if indeed there are side effects) would be minitech's solution: just change the |= to =.
Or, if there are no side effects to the someOtherCase expression, use Jakub Konecki's solution : someCase || someOtherCase.
Interesting - that looks like it's doing the equivalent:
tmp = tmp | true;
Which will always set tmp to true.
foo |= true is a short version of foo = foo | true.
The actual code can be rewritten as
bool tmp = false;
tmp |= someCase;
tmp |= someOtherCase;
Or even better as
someCase || someOtherCase
Like the other op= operators, x |= y is equivalent (except for multiple-evaluation side effects) to x = x | y. This is a terse way of writing if (!x) x = y; or if (y) x = true;.
However, it doesn't make any sense to have a constant on the right-hand side.
x |= true is more straightforwardly written as x = true
x |= false leaves x unchanged.
why they'd do this.
Some possible explanations are:
It's a typo: They meant to write tmp = true; instead of tmp |= true;, but never noticed it because their program happened to work as expected.
The RHS was originally a variable, which was replaced with the constant true without otherwise changing the code.
tmp was originally a bitfield (for which |= makes more sense), which was later reduced to a single bit.
The ultimate result will be "If any of the cases is true, the result will be true." There is no reason that you have to use the operator though, since the || in an if would work just as well.
A clever compiler could avoid the assignment in this case, though it probably wouldn't as it shouldn't short-circuit a bitwise operation. In any event, it seems like a micro-optimization. In reality I suspect it's a hold-over pattern the author has from using bit flags (or s/he just doesn't understand how it works). It would be better as:
bool tmp = somecase || someOthercase;
(and then inline the temporary if you only use it once)
Note that, when using flags, it does make sense.
#define CONDITION_ONE 0x01
#define CONDITION_TWO 0x02
int temp = 0;
if (somecase) {
temp = CONDITION_ONE;
}
if (someOthercase) {
temp |= CONDITION_TWO;
}
for bools not so much
however for bitflags this can allow code like this:
int flags=0;
flags|=READ;
//flags|=UPDATE;
foo(arg,flags);
this allows some flags to be easily commented out (and makes the used flags a tad more readable IMO)
This is equivalent to
tmp = tmp | true;
EDIT:
Which is equal to
tmp = true;
I concur with the rest of the posters here...!
More information here
Its an expression using the |= assignment operator. Check MSDN
These operands may be simple but the difficulty of finding explanations which are definitive and complete prompted me to ask. What are the character combinations containing an operand followed by an equal sign (such as *=, -=,+=, etc), what do they do and how are they useful (especially pertaining to non-numeric fields)?
Examples as well as definitions would be greatly appreciated.
Thanks
They are usually interpreted broadly as:
x += y === x = x + y
(etc for your choice of operator)
however; some languages allow you to have a bespoke += operator*, or may interpret it differently in some scenarios; for example, in C# events, += and -= mean "subscribe via the add accessor" and "unsubscribe via the remove accessor" respectively.
Typically they are just space savers, but there can be semantic differences in some cases.
*=where I mean: very different to just the + operator and assignment
Pretty much all the answers here state that x += y; is "equivalent" to "x = x + y;".
This is not actually true. They are not exactly equivalent for several reasons.
First, side effects are only performed once. Suppose you have
class C { public string S { get; set; } }
class D
{
private static C c = new C();
static C M()
{
Console.WriteLine("hello!");
return c;
}
}
The first line below prints "hello" once, as you would expect. The second prints it twice.
D.M().S += "abc";
D.M().S = D.M().S + "abc";
Second, the type system works differently for compound assignment than for regular assignment.
short b = 1;
short c = 2;
b += c;
b = b + c;
The third line is legal. The fourth line is not; a short plus a short is an int in C#, so b = b + c is an illegal assigning of an int to a short. In this case the compound assignment is actually equivalent to b = (short)(b + c);
If this subject interests you I encourage you to read sections 7.17.2 and 7.17.3 of the C# specification.
The great advantage is that you can say:
x += y;
Instead of the more verbose:
x = x + y;
Sometimes this is nice when working with strings, as you can use += to append text to an existing string.
x += expression is roughly the same thing as x = x + (expression). In other words, it calculates the right-hand side, then applies the + operator to the left-hand side and the result, and then assigns that result back into the left-hand side.
Personally, I'm not a huge fan of them. The /= operator I find a particular menace, as there are many Pascal-related languages that use that to indicate boolean inequality. Someone familiar with that who gets mixed up and tries to use it in C ends up with compiling code that produces some of the most bizzare bugs imagineable.
However, they do come in quite handy when the left-hand side is kind of large, so repeating it would throw out more noise than enlightenment.
These are compound assignment operators. For numeric fields, they're defined to add (+=), multiply (*=), and subtract (-=) the value on the right- from the variable on the left, and assign the result to the variable on the left.
However, C++ supports "operator overloading". Meaning, for any given object, the programmer can define what happens if you write x += 12 and x happens to be an object of type Foo rather than an int. This is commonly done for string classes, so if s1 = "All this" you can write s1 += " and more" and the result will be "All this and more".
Say you have x = 5. If you want to add 1 to x, you can do it in many ways:
x = x + 1;
x += 1;
x++;
++x;
They're all equivalent, and choosing any of those should leave x with 6.
So basically, if you want to multiply, divide, or subtract from x, just change the + operator to what you want.
Sorry, I didn't see that you mentioned non-numeric fields. In C# and in C++, you can do something called an "operator overload" to give a non-numeric object the ability to utilize these compound operators with a user-defined function and/or comparison.
For instance, strings are generally treated as objects and not as primitive data types, but if you execute String s = "hello"; s += "!";, you'll see that s will contain hello!. That's because the String object has an overloaded operator for += that applies an append with the rvalue ("!"--right of the += operator) to the lvalue ("hello"--left of the += operator).
A related question on C# operator overloading:
Simple way to overload compound assignment operator in C#?
If you want an explanation try reading http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Compound-assignment_operators like someone already suggested, basically a += b; is equivalent to a = a + b;. It's shorthand to make your code easier to write and read.
Here are some examples:
/* Print all evens from 0 through 20 */
for(i = 0; i <= 20; i += 2){
printf("%d\n", i);
}
/* Slow down at a linear pace */
/* Stop after speed is 0.1 or less */
while(speed > 0.1){
speed /= 1.2;
}
speed = 0;
Those should explain it. It applies to bitwise operations as well as arithmetic, but I can't think of any simple uses off the top of my head and I don't want to confuse you. There's the old temp-less swap trick - a ^= b ^= a ^= b; - which will swap the values of a and b without you having to create a temporary variable, but I'm not sure if you know what the bitwise XOR operation is at this point, so don't read into it yet.
With regard to non-numeric fields: what the operators do is completely arbitrary. In C/++/#, you can override what an operator does, allowing you to write something like:
MyObj += MyOtherObj;
// MyObj is now null
When overloading the operators, you can really do whatever you like.