Is there a way to store an operator inside a variable? I want to do something like this (pseudo code):
void MyLoop(int start, int finish, operator op)
{
for(var i = start; i < finish; op)
{
//do stuff with i
}
}
I could then call this method like so:
MyLoop(15, 45, ++);
MyLoop(60, 10, --);
Does something like this exist in C#?
You cannot store an operator in JavaScript like you have requested. You can store a function to a variable and use that instead.
Assignment operators are used in Python to assign values to variables. a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left. There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same.
The simple assignment operator ( = ) is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables.
Variables & the assignment operator, `=` A variable is a way of keeping a handle on data. Variables can hold numerical or string data that we've encountered so far, as well any other type of data, as we'll see later. In order to create a variable in python, we use the assignment operator, = i.e. the equals sign.
I suppose something like this. You do not define the operator, but a function (lambda) which does the change for you.
void MyLoop(int start, int finish, Func<int, int> op)
{
for(var i = start; i < finish; i = op(i))
{
//do stuff with i
}
}
I could then call this method like so:
MyLoop(15, 45, x => x+1);
MyLoop(60, 10, x => x-1);
Use a Function delegate
;
Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.
void MyLoop(int start, int finish, Func<int, int> op)
{
for(var i = start; i < finish; i = op(i))
{
//do stuff with i
}
}
Then;
MyLoop(15, 45, x => ++x);
MyLoop(60, 10, x => --x);
Here is a DEMO
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With